Reputation: 19314
I have the schema below that is allowing me to create a user with a badge of "1234567" for an existing app. I expected to receive a validation error b/c of the maxlength validation.
Is there something wrong with my schema?
module.exports = function(db) {
var mongoose = require('mongoose');
var appSchema = mongoose.Schema({
name: {
type: String,
required: true,
unique: true,
},
settings: mongoose.Schema.Types.Mixed,
user: [{
badge: {
type: String,
minlength: 5,
maxlength: 5
}
}]
});
// Export the schema for the app to use
return db.model('apps', appSchema);
}
I'm trying to use
apps.findByIdAndUpdate(req.params.id, {$push: {user: req.body.user}}, {runValidators: true},callback());
to add a new user record to the array in an app document.
Upvotes: 0
Views: 1957
Reputation: 2845
Validators will only work on updates for $set and $unset operations, so I believe you will have to validate manually before the update in this case.
Upvotes: 1
Reputation: 18225
As from docs, mongoose requires an Schema to validate nested objects.
so your schema should be defined as such.
Can you try using the following definition instead?
var userSchema = mongoose.Schema({
badge: {
type: String,
minlength: 5,
maxlength: 5
}
});
var appSchema = mongoose.Schema({
name: {
type: String,
required: true,
unique: true,
},
settings: mongoose.Schema.Types.Mixed,
user: [userSchema]
});
Upvotes: 0