【问题标题】:Why I cant access findOneAndUpdate in Mongoose using a plugin override?为什么我无法使用插件覆盖在 Mongoose 中访问 findOneAndUpdate?
【发布时间】:2018-11-02 04:57:28
【问题描述】:

我正在尝试通过这样做来使用插件覆盖 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,我错过了什么?

【问题讨论】:

    标签: node.js mongoose


    【解决方案1】:

    不要使用箭头函数。

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

    Mongoose documentation 声明:

    不要使用 ES6 箭头函数 (=>) 声明方法。箭头函数明确阻止绑定this,因此您的方法将无法访问文档,并且上述示例不起作用

    【讨论】:

    • 我总是忘记箭头函数不支持这个!天哪...谢谢!
    猜你喜欢
    • 2021-07-07
    • 2021-12-03
    • 2014-10-15
    • 2021-10-27
    • 1970-01-01
    • 2020-04-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-21
    相关资源
    最近更新 更多