2014-10-09 166 views
0

我有这些相当复杂的架构在猫鼬:猫鼬:填充阵列

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被引用到用户模型。现在我想运行一个查询,从我的集合中提取一个IP文档,并使用用户架构的local路径填充所有userid字段中的email

这是我的查询代码,到目前为止,但它不工作:

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); 
    }); 

这是错误快递正显示出我:

/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) } ] 

回答

0

使用Mongoose> = 3.6的填充方式做的窍门:

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'); 
     } 
     } 

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