Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose: how to define a combination of fields to be unique?

Tags:

mongoose

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?

like image 707
martinpaulucci Avatar asked Apr 17 '13 13:04

martinpaulucci


People also ask

What does unique do in Mongoose?

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.

What is $in in 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.

What is trim true in Mongoose Schema?

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.

What is Schema and model in Mongoose?

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.


1 Answers

You can define a unique compound index using an index call on your schema:

person.index({ firstName: 1, lastName: 1}, { unique: true }); 
like image 182
JohnnyHK Avatar answered Sep 30 '22 12:09

JohnnyHK