nested object values are not validated with save() when to insert model
i have an unexpected behavier when validating an object with nested objects. the validation function gets not called when to insert new record. values in first level get validated in both cases.
(using mongoose 3.8.6)
var blogSchema = Schema({
title: String,
meta: {
votes: Number,
favs: Number,
abc: String
}
});
var Blog = mong1.model('Blog', blogSchema);
Blog.schema.path('title').validate(function (value) {
return value.length < 100;
}, 'Invalid title');
Blog.schema.path('meta.votes').validate(function (value) {
return value > 100;
}, 'Invalid meta.votes');
// insert
var blog = new Blog();
blog.title = 'title';
blog.meta = {votes: 22, favs: 444, abc: 'foo'};
blog.save(); // no validation error on meta.votes, but expected
// update
Blog.findById(data._id, function (err, blog) {
blog.meta.votes = 22;
blog.save(); // validation error on meta.votes
has anybody looked into this issue yet?
the issue is that "title" gets validated both times, whereas "meta.votes" only gets validated in update.
I get this issue as well. Any workaround?
Not sure yet, I'll investigate when I get a chance.
I believe I have also noticed this problem, it would at least explain why some fields are passing validation despite the fact they should fail.
Having exact same problem. What's the recommended workaround?
Workaround for now is to use either
var blog = new Blog({ title: 'title', meta: {votes: 22, favs: 444, abc: 'foo'} });
Or
blog.meta.votes = 22;
Has this bug still not been fixed? I have just hit the same issue.
Looking more closely into it, this was fixed with #4111 in 4.4.16. Below script errors out correctly since that release:
var mongoose = require('mongoose');
mongoose.set('debug', true);
mongoose.connect('mongodb://localhost:27017/test');
var blogSchema = mongoose.Schema({
title: String,
meta: {
votes: Number,
favs: Number,
abc: String
}
});
var Blog = mongoose.model('Blog', blogSchema);
Blog.schema.path('title').validate(function (value) {
return value.length < 100;
}, 'Invalid title');
Blog.schema.path('meta.votes').validate(function (value) {
return value > 100;
}, 'Invalid meta.votes');
// insert
var blog = new Blog();
blog.title = 'title';
blog.meta = {votes: 22, favs: 444, abc: 'foo'};
blog.save(function(error) {
console.log('error', error);
process.exit(0);
});