【问题标题】:Mongoose MongoDB Objects undefinedMongoose MongoDB 对象未定义
【发布时间】:2016-12-05 21:13:24
【问题描述】:

我遇到了一个奇怪的问题。我已经开始使用 MongoDB,但很可能是我做错了什么。

我有以下模型设置:

var cartSchema = mongoose.Schema({
    owner: { type: Schema.Types.ObjectId, ref: 'users' },
    productline:  [{ type: Schema.Types.ObjectId, ref: 'Productline' }]
});

var productlineSchema = mongoose.Schema({
    cart: { type: Schema.Types.ObjectId, ref: 'Cart' },
    product: { type: Schema.Types.ObjectId, ref: 'products' },
    quantity: Number
});

最初,当用户注册时,购物车设置为一个空数组,但随后我们向其中添加了 Productline 对象(因为我可以在我的 GUI 中看到其中的数据,所以这很有效。

我正在尝试读取打算从 cart -> productline -> product

访问的名称值
for (var i=0; i < cartModel.productline.length; i++) {
    console.log(cartModel.productline[i].product.name);
}

但是得到 TypeError: Cannot read property 'name' of undefined 正好在该行,这意味着 product == "undefined"

但是,当我使用 MongoDB Compass 签入我的 MongoDB 时,我可以看到它们之间实际上存在联系,据我所知,id 看起来很准确,所以它应该能够读取它.

所以要么我试图以错误的方式达到价值,cartModel.productline[0].product.name

或者我的代码没有意识到对象已经更新,这很奇怪,因为我什至确保使用Cart.findOne(query, function(err, cartModel) { ... } 来确保我从数据库中得到一个新对象。

有人有什么想法吗?如果需要,我很乐意发布更多代码,我只是试图找到上面最相关的部分,但我可能会在其他地方遗漏一些东西......

【问题讨论】:

    标签: node.js mongodb mongoose mongoose-schema mongoose-populate


    【解决方案1】:

    我实际上设法自己解决了这个问题。对于嵌套对象有问题的人,我建议您查看 mongoose-deep-populate 插件:https://github.com/buunguyen/mongoose-deep-populate

    这对我帮助很大,我的最终查询结果如下:

    Cart.findOne({_id: cart}).deepPopulate('productline.product').exec(function (err, docs) {
        // docs is JSON data which can be used to reach the nested data.
    });
    

    【讨论】:

      【解决方案2】:

      我最近也遇到类似的错误

      演示

      当我使用时:.populate('productline')

      Cart.findOne({_id: cart}).populate('productline').exec(function(err, docs) {
         /* docs.productline items represent the correct model but their 
            fields are undefined except the `_id` */
      })
      

      解决方案

      当我使用时:.populate({path: 'productline'})

      Cart.findOne({_id: cart}).populate({path: 'productline'}).exec(function(err, docs) {
         /* docs.productline items represent the correct model with all properties
            fetched with the correct values */
      })
      

      其他解决方案

      http://mongoosejs.com/docs/populate.html 的这个例子帮助了我

      Story
          .find(...)
          .populate({
              path: 'fans',
              match: { age: { $gte: 21 }},
              select: 'name -_id', /* populates only these fields in the `fans` collection */
              options: { limit: 5 }
          })
          .exec()
      

      【讨论】:

        猜你喜欢
        • 2021-07-10
        • 1970-01-01
        • 1970-01-01
        • 2019-07-12
        • 2020-08-20
        • 2021-07-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多