简体   繁体   English

如何填充嵌套数组引用? 猫鼬

[英]how to populate nested array ref? mongoose

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 我尝试了类似的方法,以及其他一些方法,例如path: products.productpath: products.product._id和类似的方法

but all I can get is the _id , it doesn't populate the whole thing. 但是我能得到的只是_id ,它并没有填充整个内容。

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 编辑:这就是文档在db中对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
}
.populate({ path: 'nested', populate: { path: 'deepNested' }});

其中nested是第一电平ref和deepnested是REF的第一电平的参考文献

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 根据用于填充文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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