Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose make Array required

Tags:

I've got a mongoose model that looks something like this:

var ProjectSchema = new Schema({     name: { type: String, required: true },     tags: [{ type: String, required: true }] }); 

I want it to be required for a project to have at least one tag. However when I save a new project without a tags array, mongoose does not throw an error:

var project = new Project({'name': 'Some name'}); project.save(function(err, result) {     // No error here... }); 

What am I missing here? How can I specify an array to be required?

like image 348
benjiman Avatar asked Apr 26 '16 09:04

benjiman


People also ask

What is $Push in mongoose?

The $push operator appends a specified value to an array. The $push operator has the form: { $push: { <field1>: <value1>, ... } } To specify a <field> in an embedded document or in an array, use dot notation.

What is validation mongoose?

Validation is defined in the SchemaType. Validation is middleware. Mongoose registers validation as a pre('save') hook on every schema by default. You can disable automatic validation before save by setting the validateBeforeSave option. You can manually run validation using doc.

What is enum in mongoose?

Mongoose has several inbuilt validators. Strings have enum as one of the validators. So enum creates a validator and checks if the value is given in an array. E.g: const userSchema = new mongoose. Schema({ userType: { type: String, enum : ['user','admin'], default: 'user' }, })

What is Mongoose unique validator?

mongoose-unique-validator is a plugin which adds pre-save validation for unique fields within a Mongoose schema. This makes error handling much easier, since you will get a Mongoose validation error when you attempt to violate a unique constraint, rather than an E11000 error from MongoDB.


1 Answers

Mongoose 5.x

https://mongoosejs.com/docs/migrating_to_5.html#array-required

tags: {     type: [String],     validate: v => Array.isArray(v) && v.length > 0, } 

Mongoose 4.x

One-liner would be:

tags: {type: [String], required: true} 

SchemaTypes

like image 123
Yu-An Chen Avatar answered Sep 28 '22 01:09

Yu-An Chen