Set composite key in mongodb through mongoose using Node.js

In this post we will see how to maintain unique value in mongoDb in our Node.js project. Using unique key property of mongoose schema we can avoid column level duplicate value. For example consider Role collection have role name and description column. Here role name should not repeated. In SQL using unique constrain we can do that. Let see how to do it in monode.js project.
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var roleSchema = new Schema({
name: {type:String, required:true,unique:required}
description: {type:String}
});
var model = mongoose.model(role, roleSchema);
To save record in mongodb roles collection
var roleData =[
{“name”:”Admin”,” description”:”Admin role”},
{“name”:”Employee”,” description”:”Employee role”}];
roleData.forEach(function(data){
model.insert(data, function (err, resul) {
console.log(resul._Id);
});
});
Now let see how to maintain unique value in collection based on combination of more than one column.Let conceder multi-tenant application. In this use case each tenant have separate roles. Roles may or may not same in both tenant.
Let see the example.
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var roleSchema = new Schema({
name: {type:String, required:true },
tenant : {type:String, required:true },
description: {type:String}
});
roleSchema.index({name: 1, tenant: 1}, { unique: true });
var model = mongoose.model(role, roleSchema);
To save record in mongodb roles collection
var roleData =[ {“name”:”Admin”,” description”:”Admin role”,”tenant”:”tenant1”},
{“name”:”Employee”,” description”:”Employee role”,”tenant”:”tenant1”},
{“name”:”Admin”,” description”:”Admin role”,”tenant”:”tenant2”},
{“name”:”Employee”,” description”:”Employee role”,”tenant”:”tenant2”}];
roleData.forEach(function(data){
model.insert(data, function (err, resul) {
console.log(resul._Id);
});
});