猫鼬:填充数组

时间:2014-10-09 23:03:40

标签: mongodb express mongoose

我在Mongoose中有这些相当复杂的模式:

var IPSchema = mongoose.Schema({

    aktuell: {},
    historie: [
        {
        _id:        false,
        date:       { type: Date, default: Date.now },
        changed:    {},
        deleted:    { type: Boolean, default: false },
        userid:     { type: mongoose.Schema.Types.ObjectId, ref: 'User' }
       }
   ]
});

var userSchema = mongoose.Schema({
        local : {
            email        : String,
            password     : String
       }
});

module.exports = mongoose.model('IP', IPSchema);
module.exports = mongoose.model('User', userSchema);

如您所见,路径IP.historie.userid被引用到用户模型。现在,我想运行一个Query,该查询从我的集合中获取IP文档,并使用用户模式的userid路径填充emaillocal个字段。

到目前为止,这是我的查询代码,但它无效:

return IP.findById(req.params.id, function(err, ip) {

  User.populate(ip, {path: 'historie.userid', model: 'User'}, function(err, ip){
    console.log(ip.historie.userid.local.email);
  });

这是Express给我看的错误:

/var/www/kreditoren/routes/routes.js:106
        console.log(ip.historie.userid.local.email);
                      ^
TypeError: Cannot read property 'historie' of undefined

请注意,historie是一个数组,包含许多条目,例如:

historie: 
   [ { changed: [Object],
       userid: 5431ca5eb8a0c9ed34775f51,
       deleted: false,
       date: Thu Oct 09 2014 22:06:59 GMT+0200 (CEST) },
     { changed: [Object],
       userid: 5431ca5eb8a0c9ed34775f51,
       deleted: false,
       date: Thu Oct 09 2014 21:59:27 GMT+0200 (CEST) },
     { changed: [Object],
       userid: 54340279407667e53192c92a,
       deleted: false,
       date: Thu Oct 02 2014 13:59:30 GMT+0200 (CEST) } ]

1 个答案:

答案 0 :(得分:0)

使用来自Mongoose> = 3.6的populate做了诀窍:

IP.findById(req.params.id).populate('historie.userid').exec(function(err, ip) {

      for (var i=ip.historie.length-1, l=0; l<=i; i--) {

        if (ip.historie[i].userid !== null) {
          console.log(rec_hist[i].userid.local.email);
        } else {
          console.log('user unknown');
        }
      }

从用户模型中的数据输出电子邮件字段,甚至检查用户是否存在。