【问题标题】:How to call schema method inside another method in the same model using mongoose如何使用猫鼬在同一模型中的另一个方法中调用模式方法
【发布时间】:2022-11-11 03:20:08
【问题描述】:

我有一个名为“通知”的模型,它有两种方法。我想在另一个方法中调用一个方法并使用猫鼬查询相同的模型。

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const NotificationSchema = new Schema({
    code: { type: 'string', required: true, unique: true },
    name: { type: 'string', required: true }
}, collection : "notification");

NotificationSchema.methods.MethodA = async () => {
   // querying the same model
   let query = await this.find({"code" : "abc"}).lean();
   this.MethodB(); 
};

NotificationSchema.methods.MethodB = () => {
   console.log("this is methodB");
};

module.exports = mongoose.model("Notification", NotificationSchema);

现在,无法查询相同的模型并且在方法中调用方法会引发错误

this.methodB is not a function

【问题讨论】:

    标签: node.js mongodb express mongoose


    【解决方案1】:

    您能否尝试使用好的旧函数定义而不是 es6 箭头函数定义,如下所示?

    NotificationSchema.methods.MethodA = async function() {
       // querying the same model
       let query = await this.find({"code" : "abc"}).lean();
       this.MethodB(); 
    };
    
    NotificationSchema.methods.MethodB = function() {
       console.log("this is methodB");
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-08-17
      • 2021-05-24
      • 1970-01-01
      • 2015-07-11
      • 2021-11-14
      • 1970-01-01
      相关资源
      最近更新 更多