Here's my model:
'use strict';
var nested = new Schema({
name: String
});
var test = new Schema({
url : {
type : String,
// First validation
validate : [validator.isURL, 'Invalid URL']
},
array : [
{
type: nested,
// Second Validation
validate: [function(value) {console.log("CALLED"); return value.length <=3;}, 'Too long']
}
]
});
module.exports = Parent.discriminator('Test', test);;
Here's how I create a new document:
Test.findOrCreate({url: url}, function(err, model, created) {
if (created) {
model.array = whatever;
}
model.save(function(err) {
if (err) {return res.status(422).json(err);}
next();
});
});
And here's the update:
Test.findByIdAndUpdate(id, {$set: {array: whatever}}, {new: true, runValidators: true}, function(err, model) {
if (err) {
return res.status(422).json(err);
}
res.status(200).json(model);
});
Assume whatever
contains an array with length 4 on both cases (new and update).
When creating a new model, both validations work as expected and I get an error. However, when using findByIdAndUpdate
, only the first validation is run and the one on the array
attribute is ignored (it's not even called). What gives?
runValidators
options is set tofalse
by default, but I've set it totrue
on my code, which probably allows to run the first one, but not the second (the one on the subdocuments). It runs pretty much all validators on my model except the one on the subdocument's array. Is there a better way to do this? I need to update my documents through a PUT (actually a PATCH), and the only other alternative I can see is usingfind
and thensave
, which makes the purpose offindByIdAndUpdate
quite confusing to me. – Fai