For example if I have this schema
var userSchema = mongoose.Schema({
username: String,
email: String,
password: String,
_todo: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Todo'}]
});
I would like the username to be a unique key that cannot be duplicated by other users. How can I do this?
The unique option tells Mongoose that each document must have a unique value for a given path. For example, below is how you can tell Mongoose that a user's email must be unique. const mongoose = require('mongoose'); const userSchema = new mongoose.
var SimSchema = new Schema({ msisdn : { type : String , unique : true, required : true }, imsi : { type : String , unique : true, required : true }, status : { type : Boolean, default: true}, signal : { type : Number }, probe_name : { type: String , required : true } });
_id field is auto generated by Mongoose and gets attached to the Model, and at the time of saving/inserting the document into MongoDB, MongoDB will use that unique _id field which was generated by Mongoose.
In MongoDB, all documents are unique because of the _id field or path that MongoDB uses to automatically create a new document. For this reason, finding a document is easy with Mongoose. To find a document using its _id field, we use the findById() function.
You can add a constraint with the unique
attribute. This will also add a "unique" index for the field to your collection:
var userSchema = mongoose.Schema({
username: { type: String, unique: true },
email: String,
password: String,
_todo: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Todo'}]
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With