Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to make a variable a unique key in mongoose?

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?

like image 933
Monece Solis Avatar asked Mar 24 '14 06:03

Monece Solis


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.

How do I create a unique field in MongoDB schema?

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 } });

Does Mongoose auto generate ID?

_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.

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


1 Answers

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'}]
});
like image 103
Neil Lunn Avatar answered Oct 12 '22 20:10

Neil Lunn