调用Mongoose Schema定义的实例方法时触发TypeError错误
解决Mongoose实例方法调用时的TypeError问题
嘿,这个问题很常见——你在定义Mongoose实例方法的时候用错了语法,导致方法没有挂载到文档实例上,所以才会出现a.getChildren is not a function的错误!
错误原因
Mongoose中定义实例方法需要用schema.methods(复数形式)来挂载方法,或者使用schema.method(methodName, function)的语法。而你当前用的areaSchema.method({...})并不是正确的写法,Mongoose无法识别这个方式来注册实例方法,自然就找不到getChildren啦。
另外还有个小细节要注意:你代码里的exec.then应该是exec().then,exec()是一个方法,必须加括号才能返回Promise,不然也会引发后续错误。
修复方案
下面给你两种正确的实例方法定义方式,选一种就行:
方式1:使用methods对象批量定义
areaSchema.methods = { getChildren: function() { return new Promise((resolve, reject) => { this.model('Area').find({path: {$regex: '/' + this.path + '/'}}) .exec() // 这里要加括号调用exec方法 .then((areas) => { resolve(areas); }) .catch((error) => { reject(error); }); }); } }; module.exports = Area;
方式2:使用method()单独定义单个方法
areaSchema.method('getChildren', function() { return new Promise((resolve, reject) => { this.model('Area').find({path: {$regex: '/' + this.path + '/'}}) .exec() // 同样要加括号 .then((areas) => { resolve(areas); }) .catch((error) => { reject(error); }); }); }); module.exports = Area;
额外优化(可选)
其实Mongoose的查询本身就返回Promise,你可以不用手动包裹Promise,简化代码:
areaSchema.methods.getChildren = function() { return this.model('Area').find({path: {$regex: '/' + this.path + '/'}}).exec(); };
这样修改之后,不管是从Area.findOne()返回的文档实例,还是你手动new Area()创建的实例,都能正常调用getChildren()方法啦!
内容的提问来源于stack exchange,提问作者Shruti
相关产品推荐
相关产品推荐

