Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose schema property with specific values

Here's my code:

var userSchema = new mongoose.Schema({   email: String,   password: String,   role: Something }); 

My goal is to define the role property to have specific values ('admin', 'member', 'guest' and so on..), what's the better way to achieve this? Thanks in advance!

like image 583
cl0udw4lk3r Avatar asked Nov 08 '12 07:11

cl0udw4lk3r


People also ask

Can I set default value in Mongoose schema?

As mentioned by user whoami, mongoose only sets defaults on insert. If you are using mongoose 4. x and up and MongoDB 2.4. 0 and up you can opt-in to setting default values on update too.

What does $Set do in Mongoose?

The $set operator replaces the value of a field with the specified value.

What is __ V in MongoDB?

Posted On: Jun 24, 2021. In Mongoose the “_v” field is the versionKey is a property set on each document when first created by Mongoose. This is a document inserted through the mongo shell in a collection and this key-value contains the internal revision of the document.

What is ObjectId in Mongoose?

ObjectId . A SchemaType is just a configuration object for Mongoose. An instance of the mongoose. ObjectId SchemaType doesn't actually create MongoDB ObjectIds, it is just a configuration for a path in a schema.


1 Answers

You can do enum.

var userSchema = new mongoose.Schema({   // ...   , role: { type: String, enum: ['admin', 'guest'] } }  var user = new User({  // ...  , role: 'admin' }); 
like image 174
chovy Avatar answered Sep 29 '22 02:09

chovy