有没有一种更干净的方法来在Mongoose中填充嵌套对象架构?

时间:2019-06-08 21:03:42

标签: node.js mongodb express mongoose

我正在创建一个具有多个角色的用户的订购系统。每个用户都有多个关联的订单。每个订单都有一个名为“ Peeps”的嵌套对象,该对象具有3个属性:客户,交货,物流。

我正在尝试填充User模型,我找到了一种在Orders Peeps对象中填充用户的方法(请检查下面的模式),但是它很麻烦,因为它需要多次填充调用,而且我想知道是否有一个更好的方法。

我也不完全了解该模式,但是我只是在尝试一些东西,偶然发现了这个小问题。

模式


const UserSchema = Schema({
    Name: {
        type: String,
        default: "John Doe"
    },
    Password: {
        type: String,
        default: "password"
    },
    Email: {
        type: String,
        unique: true
    },
    Phone: {
        type: String,
        unique: true
    },
    Orders: [{
        type: Schema.Types.ObjectId,
        ref: "orders"
    }]
});

const OrderSchema = Schema({

    Peeps: {
        Client: {
            type: Schema.Types.ObjectId,
            ref: "users"
        },
        Logistics: {
            type: Schema.Types.ObjectId,
            ref: "users"
        },
        Delivery: {
            type: Schema.Types.ObjectId,
            ref: "users"
        },
    },
    LocationUpdates: [{
        type: LocationUpdateSchema,
        ref: "locationupdates"
    }]
});

填充数据的查询代码(可以,但是没问题)

const query = await Users.findOne({ Email: "john.doe@gmail.com" })
                .populate({
                    path: "Orders",
                    populate: {
                        path: "Persons.Client"
                    }
                })
                .populate({
                    path: "Orders",
                    populate: {
                        path: "Persons.Delivery"
                    }
                })
                .populate({
                    path: "Orders",
                    populate: {
                        path: "Persons.Logistics"
                    }
                });


0 个答案:

没有答案
相关问题