mongoose – 传递参数预保存 – 在更新保存中不起作用
我试图传递一个参数来预先保存一个mongoose模型中间件,如:
subject.save({ user: 'foo', correlationId: 'j3nd75hf...' }, function (err, subject, count) { ... });
它被传递给两个预存中间件
第一:
schema.pre('save', function (next) { // do stuff to model if (arguments.length > 1) next.apply(this, Array.prototype.slice.call(arguments, 1)); else next(); });
然后:
schema.pre('save', function(next, metadata, callback) { // ... // create history doc with metadata // ... history.save(function(err, doc) { if(err) throw err; if (typeof metadata == 'object') next(callback); else next(); }); });
它不能保存从数据库中获取的现有模型,但它在新创build的模型上工作。
如果我删除参数,它确实工作。
所以如果我打电话
subject.save(function (err, subject, count) { ... });
…它的工作。
看起来callback从来没有实际callback。 所以也许它假设第一个参数是save()更新的callback。
对于创build,它可以使用传递参数
(new models.Subject(subjectInfo)).save({ user: user, correlation_id: correlationId }, function (err, subject, count) { if (err) throw err; ... });
任何想法,为什么它的save()创build,但不保存()更新?
谢谢!!
经过search和search,这是我推荐的。
而是在虚拟领域做工作。
schema.virtual('modifiedBy').set(function (userId) { if (this.isNew()) { this.createdAt = this.updatedAt = new Date; this.createdBy = this.updatedBy = userId; } else { this.updatedAt = new Date; this.updatedBy = userId; } });
如果这不能帮助你,你可能会发现这个其他答案有帮助: https : //stackoverflow.com/a/10485979/1483977
或者这个github问题:
https://github.com/Automattic/mongoose/issues/499
或者这个 。
model.save()
的参数是1,该参数应该是callback函数。 我仍然不完全确定如何设置所有的东西,因为你编写代码的风格有点异样。 该模型的保存方法只能像这样callback:
Subject.findOne({ id: id }, function (err, subject) { subject.set('someKey', 'someVal'); // You can only pass one param to the model's save method subject.save(function (err, doc, numAffected) { }); });
对于mongoose更新,我们做:
Subject.update({ id: id}, function (err, numAffected) { // There is no doc to save because update() bypasses Subject.schema });
此链接显示Model.save()的定义。 你会注意到它只接受一个参数: https : //github.com/LearnBoost/mongoose/blob/3.8.x/lib/model.js#L167