gpt4 book ai didi

node.js - 为什么我无法使用插件覆盖访问 Mongoose 中的 findOneAndUpdate?

转载 作者:太空宇宙 更新时间:2023-11-03 21:51:41 25 4
gpt4 key购买 nike

我试图通过这样做使用插件覆盖 findOneAndUpdate 方法:

// Messages is a Mongoose Model
await Messages.newFindOneAndUpdate(query, payload, options);

在消息架构定义中,我有:

MessagesSchema.plugin(require('../util/schema-api-aware-plugin'));

该插件只是声明静态方法newFindOneAndUpdate:

module.exports = (schema) => {

schema.statics.newFindOneAndUpdate = async (query, data, options) => {
const me = this;

try {
return await me.findOneAndUpdate(query, data, options);
}
catch (err) {
errorManager(err, res);
return null;
}
}

};

当我运行它时,我收到类型错误me.findOneAndUpdate is not a function。该模型有效,插件按其应有的方式附加,存在静态方法,但由于某种原因,应该是 thisme 没有方法>findOneAndUpdate,我错过了什么?

最佳答案

不要使用箭头函数。

Mongoose 扩展(如插件和实例方法)依赖于 Mongoose 能够设置 this,箭头函数不支持此功能。

Mongoose documentation状态:

Do not declare methods using ES6 arrow functions (=>). Arrow functions explicitly prevent binding this, so your method will not have access to the document and the above examples will not work.

关于node.js - 为什么我无法使用插件覆盖访问 Mongoose 中的 findOneAndUpdate?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53109018/

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