moongose 深度填充嵌套字段

问题描述 投票:0回答:1

我有3张原理图 预订方案、购物车方案和订单方案。购物车包含书籍列表及其数量。订单模式是 _id Cart.product._id 的数组。我如何填充以及可能吗?或者我的架构有错误

const BookSchema = new Schema(
    {
        title: { type: String, required: true, uniq: true },
        description: { type: String, required: true },
    },
    { versionKey: false }
);

const CartSchema = new Schema(
    {
        userId: { type: Schema.Types.ObjectId, ref: "User", required: true },
        products: [
            {
                product: {
                    type: Schema.Types.ObjectId,
                    ref: "Book",
                },
                quantity: { type: Number },
            },
        ],
    },
    { versionKey: false }
);

const OrderSchema = new Schema(
    {
        userId: { type: Schema.Types.ObjectId, ref: "User", required: true },
        orders: [
            {
                products: [
                    {
                        type: Schema.Types.ObjectId,
                        ref: "Cart",
                    },
                ],
                status: {
                    type: Schema.Types.Number,
                    enum: Object.values(STATUS),
                },
            },
        ],
    },
    { versionKey: false }
);

我尝试填充,但它要么返回一个数组。或者,如果我传递购物车方案的_id,它会插入购物车。我需要有来自 Cart.products 模式的对象。

这就是我所做的。

    path: "orders.products",
    populate: {
        path: "products",
        populate: {
            path: "product",
            model: "Book",
        },
    },
});```

expected behavior

常量顺序 = { 用户ID: 1, 命令: [ { 产品: [ { 产品: { 作品名称:《我们》 //其他字段 }, 数量: 1, }, ], 状态:“按顺序” }, { 产品: [ { 产品: { 片名:《1984》 //其他字段 }, 数量: 2, }, ], 状态:“已交付” }, ], };````

javascript mongodb express mongoose backend
1个回答
0
投票

您的问题不是很清楚,您能否提供一个示例输出,说明您到底想要从查询中得到什么?

© www.soinside.com 2019 - 2024. All rights reserved.