nested object values are not validated with save() when to insert model #1919

Open
sharkboy1976 opened this Issue Feb 6, 2014 · 6 comments

5 participants

@sharkboy1976

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
@sharkboy1976

has anybody looked into this issue yet?

the issue is that "title" gets validated both times, whereas "meta.votes" only gets validated in update.

@refaelos

I get this issue as well. Any workaround?

@vkarpov15 vkarpov15 added the bug? label Oct 6, 2014
@vkarpov15

Not sure yet, I'll investigate when I get a chance.

@c1moore

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.

@valentinkostadinov

Having exact same problem. What's the recommended workaround?

@vkarpov15 vkarpov15 added this to the 3.8.21 milestone Nov 19, 2014
@vkarpov15

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;
@vkarpov15 vkarpov15 added confirmed-bug and removed bug? labels Dec 5, 2014
@vkarpov15 vkarpov15 removed this from the 3.8.21 milestone Dec 5, 2014
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment