If I had a schema like this:
var person = new Schema({ firstName: String, lastName: String, });
I'd like to ensure that there is only one document with the same firstName and lastName.
How can I accomplish 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.
The value of the $in operator is an array that contains few values. The document will be matched where the value of the breed field matches any one of the values inside the array.
If you add { type: String, trim: true } to a field in your schema, then trying to save strings like " hello" , or "hello " , or " hello " , would end up being saved as "hello" in Mongo - i.e. white spaces will be removed from both sides of the string.
Mongoose Schema vs. Model. A Mongoose model is a wrapper on the Mongoose schema. A Mongoose schema defines the structure of the document, default values, validators, etc., whereas a Mongoose model provides an interface to the database for creating, querying, updating, deleting records, etc.
You can define a unique compound index using an index
call on your schema:
person.index({ firstName: 1, lastName: 1}, { unique: true });
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