Mongoose同模型方法内调用其他schema方法及查询报错问题
问题根因
代码报错有三个直接原因:
- 禁止用箭头函数定义Mongoose Schema方法:箭头函数不会绑定自身执行上下文的
this,会继承外层作用域的this,完全无法指向Mongoose自动绑定的文档实例/模型对象,直接导致this.find不存在、this.MethodB is not a function两个错误。 - Schema配置语法错误:
collection: "notification"没有放在Schema构造函数的第二个配置对象内部,会直接触发语法报错。 - 方法挂载位置和使用场景不匹配:
methods上挂载的是实例方法,this默认指向单个文档实例,本身不直接挂载模型的全局查询方法find,需要手动通过this.model()获取模型对象才能发起查询;如果是不需要绑定单个文档的全局操作,应该把方法挂载到statics上作为静态方法,静态方法的this直接指向当前模型。
修正代码
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" }); // 修正Schema配置写法 // --------------- 实例方法写法 --------------- // 必须使用普通function定义,不要用箭头函数 NotificationSchema.methods.MethodA = async function() { // 实例方法内通过this.model()获取当前模型,即可发起同模型查询 const queryResult = await this.model("Notification").find({ code: "abc" }).lean(); console.log('查询结果:', queryResult); // 同实例方法可直接通过this调用 this.MethodB(); }; NotificationSchema.methods.MethodB = function() { console.log("this is methodB"); }; // --------------- 静态方法写法(推荐用于全局模型操作场景)--------------- // 如果方法不需要绑定单个文档,直接做模型层面的查询/操作,用静态方法更方便 /* NotificationSchema.statics.MethodA = async function() { // 静态方法this直接指向当前模型,可直接调用find等查询方法 const queryResult = await this.find({ code: "abc" }).lean(); console.log('查询结果:', queryResult); // 同模型静态方法可直接通过this调用 this.MethodB(); }; NotificationSchema.statics.MethodB = function() { console.log("this is static methodB"); }; */ module.exports = mongoose.model("Notification", NotificationSchema);
调用注意事项
- 实例方法需要先获取到具体的文档实例才能调用:
// 先查询一条文档拿到实例 const notificationInstance = await Notification.findOne({ code: "test" }); // 再调用实例方法 await notificationInstance.MethodA();
- 静态方法可以直接在模型上调用,不需要提前查询实例:
await Notification.MethodA();
内容的提问来源于stack exchange,提问作者Nay Oo Lwin
相关产品推荐
相关产品推荐

