Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Restrict mongoose field values

I'm trying to create:

var mongoose = require('mongoose');

var FeelingSchema = new mongoose.Schema({
    userId: String,
    feelingDate: Date,
    feelingTimeOfDay: String,
    feelingValue: String
  }
);

How do I restrict the value of the field feelingValue to a limited set, say ['happy', 'angry', 'shocked']

I'm using version 3.8.23 of mongoose

like image 736
lalitb Avatar asked Apr 25 '15 01:04

lalitb


People also ask

How do I limit the number of files in Mongoose?

The limit() method in Mongoose is used to specify the number or a maximum number of documents to return from a query.

Can I set default value in Mongoose schema?

You can also set the default schema option to a function. Mongoose will execute that function and use the return value as the default.

What does trim do in Mongoose?

It's basically there to ensure the strings you save through the schema are properly trimmed.

What is __ V 0 in Mongoose?

The __v field is called the version key. It describes the internal revision of a document. This __v field is used to track the revisions of a document. By default, its value is zero ( __v:0 ). If you don't want to use this version key you can use the versionKey: false as mongoose.


1 Answers

You can constrain a string field to a set of enumerated values with the enum attribute in the schema definition:

var FeelingSchema = new mongoose.Schema({
    userId: String,
    feelingDate: Date,
    feelingTimeOfDay: String,
    feelingValue: { type: String, enum: ['happy', 'angry', 'shocked'] }
  }
);
like image 135
JohnnyHK Avatar answered Nov 08 '22 17:11

JohnnyHK