gpt4 book ai didi

node.js - Mongoose - 将参数传递给预保存 - 在更新保存中不起作用

转载 作者:太空宇宙 更新时间:2023-11-03 22:47:45 24 4
gpt4 key购买 nike

我正在尝试传递一个参数来在 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();
});
});

它不适用于保存从数据库获取的现有模型,但它适用于新创建的模型。

如果我删除该参数,它确实有效。

所以如果我打电话...

subject.save(function (err, subject, count) {
...
});

...它确实有效。

看起来回调实际上从未回调。所以也许假设第一个参数是 save() 更新的回调。

对于创建,它确实可以传递参数

(new models.Subject(subjectInfo)).save({ user: user, correlation_id: correlationId }, function (err, subject, count) {
if (err) throw err;

...
});

关于为什么它适用于创建时的 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;
}
});

如果这对您没有帮助,您可能会发现其他答案有帮助:https://stackoverflow.com/a/10485979/1483977

或者这个 github 问题:

https://github.com/Automattic/mongoose/issues/499

或者this .

关于node.js - Mongoose - 将参数传递给预保存 - 在更新保存中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20525896/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com