【问题标题】:mongoose populate and return a document with path as a list猫鼬填充并返回带有路径作为列表的文档
【发布时间】:2020-12-25 13:51:05
【问题描述】:

我正在使用 mongoose 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"

任何帮助将不胜感激。提前致谢

【问题讨论】:

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


    【解决方案1】:

    Mongoose 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;
    }
    

    【讨论】:

      【解决方案2】:

      mongoose populate 方法只接受一个字符串,这是您要引用的字段的名称。因此,您不能传递包含要填充的所有字段名称的列表。您需要在单独的方法调用中传递要填充的字段的每个名称。看看下面的代码sn-p:

      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

      【讨论】:

        猜你喜欢
        • 2021-04-15
        • 2021-02-11
        • 2021-05-21
        • 2013-10-05
        • 2022-12-09
        • 2016-06-27
        • 1970-01-01
        • 1970-01-01
        • 2016-03-03
        相关资源
        最近更新 更多