Skip to content

Sub-doc array pre validate middleware fails to run on subsequent saves after create #5861

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
JasonCust opened this issue Nov 30, 2017 · 1 comment
Labels
confirmed-bug We've confirmed this is a bug in Mongoose and will fix it.
Milestone

Comments

@JasonCust
Copy link

Similar to a previously reported issue (#3884) except it appears to only happen for subdoc arrays now.

Tested on 4.13.5

var Schema = mongoose.Schema;

var childSchema = new Schema({
  name: { type: String },
  friends: [{ type: String }]
});

childSchema.pre('validate', function (next) {
    console.log('Child pre validate');
    next();
});

childSchema.pre('save', function (next) {
    console.log('Child pre save');
    next();
});

var parentSchema = new Schema({
  name: { type: String },
  children: [childSchema]
});

parentSchema.pre('validate', function (next) {
    console.log('Parent pre validate');
    next();
});

parentSchema.pre('save', function (next) {
    console.log('Parent pre save');
    next();
});

var Parent = connection.model('Parent', parentSchema);
var parent = new Parent({
  name: 'Mufasa',
  children: [{
    name: 'Simba',
    friends: ['Pumbaa', 'Timon', 'Nala']
  }]
});

parent.save({new: true}).then(function(savedParent) {
  if (savedParent) {
    console.log(savedParent);
    savedParent.children[0].friends.push('Rafiki');
    return savedParent.save({new: true});
  } else {
    throw new Error('Parent was not saved');
  }
}).then(function(updatedParent) {
  console.log(updatedParent);
}).catch(function(err) {
  console.error(err);
});

outputs:

// initial save
Parent pre validate
Child pre validate
Child pre save
Parent pre save
{
  _id: 5a1f71acc21e58e2cdc53a26,
  children: [{ friends: [ 'Pumbaa', 'Timon', 'Nala' ], name: 'Simba', _id: 5a1f71acc21e58e2cdc53a27 }],
  name: 'Mufasa',
  __v: 0
}

// subsequent save
Parent pre validate
Child pre save
Parent pre save
{
  _id: 5a1f71acc21e58e2cdc53a26,
  children: [{ friends: [ 'Pumbaa', 'Timon', 'Nala', 'Rafiki' ], name: 'Simba', _id: 5a1f71acc21e58e2cdc53a27 }],
  name: 'Mufasa',
  __v: 1
}
@vkarpov15 vkarpov15 added this to the 4.13.7 milestone Dec 7, 2017
@vkarpov15 vkarpov15 added the confirmed-bug We've confirmed this is a bug in Mongoose and will fix it. label Dec 7, 2017
@vkarpov15
Copy link
Collaborator

Thanks for the detailed repro, will fix 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
confirmed-bug We've confirmed this is a bug in Mongoose and will fix it.
Projects
None yet
Development

No branches or pull requests

2 participants