猫鼬填充并以路径为列表返回文档

时间:2020-09-07 06:41:22

标签: javascript node.js mongodb mongoose mongoose-populate

我正在使用猫鼬5.9.28和节点v12.16.1。

我需要编写一个函数,将列表作为参数,并在猫鼬模型中填充该列表。 (模型在功能上是恒定的)

我的模式:

    var schema = new mongoose.Schema({
    id : {
        type : String,
        required : true,
        unique : true,
    },
    driverId : {
        type : mongoose.Schema.Types.ObjectId,
        ref : "drivers"            
    },
    vehicleId : {
        type : mongoose.Schema.Types.ObjectId,
        ref : "vehicles"            
    },
    customerId : {
        type : mongoose.Schema.Types.ObjectId,
        ref : "customers",
        required : true            
    },
    bookedOn : {
        type : String
    },
    pickUpLocation : {
        type : String,
        required : true,
    },
    dropLocation : {
        type : String,
        required : true
    },
    paymentId : {
        type : mongoose.Schema.Types.ObjectId,
        ref : "payments"             
    },
    bookingStatusId :{
        type : mongoose.Schema.Types.ObjectId,
        ref : "booking_status"             
    },  
    goodsType : {
        type : String,
        required : true
    }     
});

在此,driverId,vehicleId,customerId,paymentId,bookingStatusId是对其他模型的引用。

我有此功能,其中refs是一个列表。

const getBookings = async (refs) => {
    const booking = await bookingModel.find().lean().populate({
                                     path : refs,
                                     select : ['-_id']
                                     ).exec()
    return booking;
}

如果我打电话给getBookings(['customerId','driverId']),我应该得到文档,其中包含已填充的客户和驱动程序详细信息,但不包括_id。

但是我得到的错误为TypeError: utils.populate: invalid path. Expected string. Got typeof "object"

任何帮助将不胜感激。预先感谢

2 个答案:

答案 0 :(得分:1)

猫鼬Model#populate接受一个path。要填充多个字段,您需要使用here in the docs所述的链接。

您可以在refs数组上运行循环以链式填充模型。像这样:

const getBookings = async (refs) => {
    let query = bookingModel.find().lean();
    refs.forEach((ref => query = query.populate({path: ref, select: ['-_id'] });
    const booking = await query.exec()
    return booking;
}

答案 1 :(得分:0)

猫鼬填充方法仅接受字符串,这是您要引用的字段的名称。因此,您无法传递包含要填充的所有字段名称的列表。您需要在单独的方法调用中传递要填充的字段的每个名称。看一下以下代码片段:

const booking = await bookingModel.find()
                           .lean()
                           .populate({ path: 'customerId', select: ['_id']})
                           .populate({ path: 'driverId', select: ['_id']})
                           .exec();

另请参见文档:https://mongoosejs.com/docs/populate.html#populating-multiple-paths

相关问题