Automattic / mongoose

MongoDB object modeling designed to work in an asynchronous environment.
https://mongoosejs.com
MIT License
26.88k stars 3.83k forks source link

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

Closed JasonCust closed 6 years ago

JasonCust commented 6 years ago

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 commented 6 years ago

Thanks for the detailed repro, will fix :+1: