Hello @Krushna_Chandra_Rout, Welcome to the MongoDB Community forum!
With Mongoose ODM, when you create a field in a schema with property unique:true
, it means that a unique constraint be created on that field. In fact it does create such an index in the database for that collection.
For example, the following code creates such data and inserts one document. I can verify the collection, the document and the unique index from mongosh
or Compass. In the shell, db.collection.getIndexes()
prints the newly created index details.
When I run the same program again, or try to insert another document with the same name: 'john'
, there is an error: MongoError: E11000 duplicate key error collection: test.records index: name_1 dup key: { name: "john" }
.
Please include the version of MongoDB and Mongoose you are working with.
Example Code:
const mongoose = require('mongoose');
const url = 'mongodb://127.0.0.1:27017/test';
mongoose.connect(url, { useNewUrlParser: true, useUnifiedTopology: true });
const Schema = mongoose.Schema;
var RecordSchema = new Schema({
name: { type: String, required: true, unique: true }
}, { collection: 'records' })
const Record = mongoose.model('Record', RecordSchema);
const r1 = Record({ name: 'john' });
r1.save(function(err) {
if (err) throw err;
console.log('r1 record saved.');
});