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?
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.
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.
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' }, })
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.
https://mongoosejs.com/docs/migrating_to_5.html#array-required
tags: { type: [String], validate: v => Array.isArray(v) && v.length > 0, }
One-liner would be:
tags: {type: [String], required: true}
SchemaTypes
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With