【问题标题】:Query another model in instance method of a different model在不同模型的实例方法中查询另一个模型
【发布时间】:2017-10-11 14:25:33
【问题描述】:

它试图在 另一个模型的实例方法中查询一个不同的 模型静态方法,并且变得未定义,尽管我在架构类之外使用相同并且它正在工作. 如需更好的概览,请参阅示例代码:

UserFormSchema.post('save', function (next) {
var form = this;
  Models.SubCategory.getById(form.subCategoryId).then(function(data){
  console.log(data);
  }).catch(function(err){
    return Promise.reject(err);
  });
});


TypeError: Cannot read property 'SubCategory' of undefined

每个 Schema 都可以为其模型定义实例和静态方法。

【问题讨论】:

  • 能不能打个码sn-p
  • 试试 this.Models.getById
  • @Sam 试过但一样
  • 在你的情况下,'this' 是表格,请检查它
  • @Sam stackoverflow.com/a/38488773/1936186,我试过了,效果很好

标签: javascript node.js mongodb mongoose


【解决方案1】:

感谢这篇文章:https://stackoverflow.com/a/38488773/1936186`

UserFormSchema.post('save', function (next) {
var form = this;
mongoose.model('SubCategory').getById(form.subCategoryId).then(function(data){
      console.log(data);
   }).catch(function(err){
     return Promise.reject(err);
   });
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-09
    • 1970-01-01
    • 2021-01-05
    • 2011-01-08
    • 2013-09-12
    • 1970-01-01
    相关资源
    最近更新 更多