【问题标题】:Mongoose: Populate ArrayMongoose:填充数组
【发布时间】:2014-12-05 00:41:23
【问题描述】:

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

这是我目前的查询代码,但它不起作用:

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

【问题讨论】:

    标签: mongodb express mongoose


    【解决方案1】:

    使用来自 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');
            }
          }
    

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

    【讨论】:

      猜你喜欢
      • 2019-01-31
      • 2019-07-28
      • 1970-01-01
      • 1970-01-01
      • 2020-06-07
      • 2015-03-26
      • 2019-02-13
      • 2019-03-28
      相关资源
      最近更新 更多