首页 > 解决方案 > Mongoose Schema 上定义的实例方法的类型错误

问题描述

我在从控制器调用模型中定义的实例方法之一时收到 TypeError。

控制器:

这是我在控制器中的代码:

var Area = require('../../models/area');

Area.findOne({_id: 'Test'}).then((a) => {
    a.getChildren().then((area) => {console.log(area)})
})

它返回此错误:

TypeError: a.getChildren is not a function

楷模:

这是我在模型中的代码:

areaSchema.method({
  getChildren: function() {
    return new Promise(function(resolve, reject) {
      this.model('Area').find({path: {$regex: '/' + this.path + '/'}}).exec.then((areas) => {
        return resolve(areas)
      }).catch((error) => reject(error))
    })
  }
})

    module.exports = Area;

节点控制台:

我也在节点控制台中尝试过:

var Area = require('./models/area')
var a = new Area({name: 'test', type: 'test'})
a.getChildren().then((area) => {console.log(area)})

它也返回相同的错误:

TypeError: a.getChildren is not a function

标签: node.jsmongoose

解决方案


推荐阅读