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
}

2 Answers 2

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

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

Sign up to request clarification or add additional context in comments.

Comments

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

2 Comments

still no luck, I believe I also tried that before but anyways I tried it again but ya, no luck
I edited my post, showing how does the document looks like. Donno why I do feel something is off

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.