0

I found this post which is quite close to my need but somehow I still can't get it to work though

Populate nested array in mongoose

It's a bit hard to explain what kind of nested ref I am talking about. I just start with the code

I have a Products Schema

const ProductSchema = new Schema(Object.assign({
    name: {type: String};
});

an order schema

const OrderSchema = new Schema(Object.assign({
    products: [ {
        product: { type: Schema.Types.ObjectId, ref: 'Products' },
        amount: { type: Number },
        total: { type: Number },
    } ],
});

I tried doing

    const order = await Orders.findOne({
        _id: 'orderId39843984203'
    }).populate({
        path: 'products',
        populate: {
            path: 'product'
        }
    });

I tried something like that, and few other ways such as path: products.product or path: products.product._id and something simliar

but all I can get is the _id, it doesn't populate the whole thing.

Can someone please give me a hand or advice how this would work?

Thanks in advance

EDIT: this is how the document looks like in db for orderSchema

{
    "_id": {
        "$oid": "5ba2e2af52f2ff3f4226015c"
    },
    "products": [
        {
            "_id": {
                "$oid": "5ba2e2ac52f22f3f4226015e"
            },
            "amount": 4,
            "total": 2940
        },
        {
            "_id": {
                "$oid": "5ba2e2ac52f2ff3f5226015d"
            },
            "amount": 1,
            "total": 840
        }
    ],
    "createdAt": {
        "$date": "2018-09-19T23:58:36.339Z"
    },
    "updatedAt": {
        "$date": "2018-09-19T23:58:36.505Z"
    },
    "__v": 0
}
Tsuna
  • 2,098
  • 6
  • 24
  • 46

2 Answers2

1
.populate({ path: 'nested', populate: { path: 'deepNested' }});

where nested is first level ref and deepnested is ref of first level of ref.

Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
0

You should be able to do it with this:

const order = await Orders.findOne({
    _id: 'orderId39843984203'
}).populate('products.product')
.exec((error, doc) => doc);

As per the docs for populate

Akrion
  • 18,117
  • 1
  • 34
  • 54
  • still no luck, I believe I also tried that before but anyways I tried it again but ya, no luck – Tsuna Sep 20 '18 at 17:09
  • I edited my post, showing how does the document looks like. Donno why I do feel something is off – Tsuna Sep 20 '18 at 17:22