简体   繁体   中英

Mongoose MongoDB Objects undefined

I've run into a strange issue. I've started to use MongoDB and it's most likely me doing something terrible wrong.

I have the following models setup:

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

Initially the Cart is setup with an empty array when the User registers, but then we add Productline objects to it later (which works since I can see data in there in my GUI.).

I'm trying to read the name value which is intended to be reached from cart -> productline -> product

for (var i=0; i < cartModel.productline.length; i++) {
    console.log(cartModel.productline[i].product.name);
}

But getting TypeError: Cannot read property 'name' of undefined on exactly that line, which means that product == "undefined" .

However, when I'm checking in my MongoDB with MongoDB Compass, then I can see that there is infact a connection between them, and the id's looks accurate as far as I can tell, so it should be able to read it.

So either I'm trying to reach the values in the wrong way, cartModel.productline[0].product.name .

Or my code doesn't realize that the object has been updated, which is strange since I even made sure to use Cart.findOne(query, function(err, cartModel) { ... } to be sure I get a fresh one from the database.

Anyone has any ideas? I'll be glad to post some more code if needed, I just tried to find the most relevant parts above, but I might be missing something somewhere else...

I actually managed to solve this by myself. For people who are having problems with nested objects, I recommend you looking into the mongoose-deep-populate plugin: https://github.com/buunguyen/mongoose-deep-populate

It helped me out a lot, and my final query ended up like this:

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

I have also encountered similar error recently

Demo

When I use: .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` */
})

Solution

When I use: .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 */
})

Other solution

This example from http://mongoosejs.com/docs/populate.html helped me

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM