简体   繁体   English

Mongoose预保存第二个保存操作未调用的子文档中间件

[英]Mongoose pre save middleware of subdocument not called on second save operation

I have a mongoose schema with a subdocument. 我有一个带有子文档的mongoose模式。 Both the parent schema and the child schema have pre save hooks. 父模式和子模式都具有预保存挂钩。 For example: 例如:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var SubSchema = new Schema( { x : Number } );
SubSchema.pre('save', function (next) {
  console.log("pre save Sub");
  next();
});

var MainSchema = new Schema( { x : Number, children : [SubSchema] } );
MainSchema.pre('save', function (next) {
  console.log("pre save Main");
  next();
});
var Main = mongoose.model('Main', MainSchema);

var m = new Main();
m.children.push( { x : 42 } );

m.save( function(err, doc) {
  console.log(doc +"\n\n");
  doc.children[0].x = 43;

  doc.save( function(err, doc2) {
    console.log(doc2 + "\n\n");
  });
});

When I run this code, I get the following output: 当我运行此代码时,我得到以下输出:

pre save Sub
pre save Main
{ __v: 0,
  _id: 50660b319aec895a50000002,
  children: [ { x: 42, _id: 50660b319aec895a50000003 } ] }


pre save Main
{ __v: 0,
  _id: 50660b319aec895a50000002,
  children: [ { x: 43, _id: 50660b319aec895a50000003 } ] }

Any reason why the pre save hook is not running for the subdocument on the second save operation? 在第二次保存操作的子文档没有运行预保存挂钩的任何原因?

This is fixed in v3.2.0, by letting you do this: 这是在v3.2.0中修复的,允许你这样做:

doc.children.set(0, {x: 43})
doc.save()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM