2017-04-24 67 views
0

这是在一个组模型中,在组模型保存预拉钩的正则表达式更新为用户搜索。但是猫鼬返回“User.find不是一个函数”,当我console.logged用户它返回一个空的对象({})。为什么我不能查询用户组内的用户保存预先挂钩?猫鼬模型是另一个模型内部的空物体保存钩子

var User = require('./User') 
... 
    _schema.pre('save', function (next) { 
     this.regex = '' 
     if (!this.users) { return next() } 
     var userIds = this.users.map(s => s._id) 
     User.find({ _id: { $in: userIds } }).select('name surname').lean().then(docs => { 
      docs.forEach(d => { 
       this.regex += (' ' + d.name + ' ' + d.surname) 
      }) 
      next() 
     }) 
    }) 
+0

这可能是由于循环依赖性User模型也可能依赖于调用它的模型。 [详细](https://stackoverflow.com/questions/44816014/mongoose-model-is-an-empty-object-inside-post-hook-of-another-model/44817920#44817920) – NERDYLIZARD

回答

0

只需移动钩子内的用户定义就可以工作。

_schema.pre('save', function (next) { 
    var User = require('./User') 
     this.regex = '' 
     if (!this.users) { return next() } 
     var userIds = this.users.map(s => s._id) 
     User.find({ _id: { $in: userIds } }).select('name surname').lean().then(docs => { 
      docs.forEach(d => { 
       this.regex += (' ' + d.name + ' ' + d.surname) 
      }) 
      next() 
     }) 
    })