And*_*nna 2 mongoose mongodb node.js
我正在尝试传递一个参数来在猫鼬模型上预先保存中间件,例如:
subject.save({ user: 'foo', correlationId: 'j3nd75hf...' }, function (err, subject, count) {
...
});
Run Code Online (Sandbox Code Playgroud)
它被传递给两个预保存中间件
第一的:
schema.pre('save', function (next) {
// do stuff to model
if (arguments.length > 1)
next.apply(this, Array.prototype.slice.call(arguments, 1));
else
next();
});
Run Code Online (Sandbox Code Playgroud)
然后:
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();
});
});
Run Code Online (Sandbox Code Playgroud)
它不适用于保存从数据库中获取的现有模型,但它适用于新创建的模型。
如果我删除参数,它确实有效。
所以如果我打电话...
subject.save(function (err, subject, count) {
...
});
Run Code Online (Sandbox Code Playgroud)
...它确实有效。
看起来回调从未真正回调。所以也许它假设第一个参数是 save() 更新的回调。
对于创建,它确实与传递参数一起工作
(new models.Subject(subjectInfo)).save({ user: user, correlation_id: correlationId }, function (err, subject, count) {
if (err) throw err;
...
});
Run Code Online (Sandbox Code Playgroud)
关于为什么它在创建时适用于 save() 而在更新时不适用于 save() 的任何想法?
谢谢!!
经过搜索和搜索,这是我推荐的。
而是在虚拟领域中进行工作。
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;
}
});
Run Code Online (Sandbox Code Playgroud)
如果这对您没有帮助,您可能会发现这个其他答案有帮助:https : //stackoverflow.com/a/10485979/1483977
或者这个github问题:
https://github.com/Automattic/mongoose/issues/499
或者这个。
| 归档时间: |
|
| 查看次数: |
7397 次 |
| 最近记录: |