【问题标题】:How to populate an field in array of Mongooese?如何填充 Mongoose 数组中的字段?
【发布时间】:2020-12-01 18:41:07
【问题描述】:

我有一个这样的集合架构:

const PrescriptionSchema = new Schema({
    patientId:{type: mongoose.Schema.ObjectId, ref: 'User'},
    prescriptionName: String,
    prescriptionNote: String,
    prescriptionDate: Date,
    diseaseId: {type: mongoose.Schema.ObjectId, ref: 'Diseases'},
    drugs: [{
        drugcateId:{type: mongoose.Schema.ObjectId, ref: 'DrugCategory'},
        quantity: Number,
        howtouse: String
    }],
    is_deleted: {type: Boolean, default: false},
    createdBy: {type: mongoose.Schema.ObjectId, ref: 'User'}
}, {
        timestamps: true,
        collection: 'prescriptions'
    }
);
export default mongoose.model('prescriptions', PrescriptionSchema );

请注意,在这个集合中,我有一个“药物”数组,这是我从“DrugCategory”获得的一组药物,在每种药物中我都有数量和使用方法......所以我将它分组(drugCateId,数量, howtouse) 在药物数组中。 当我找到一个处方时,我想在药物数组中填充 drugCateId。我该怎么做? 以下是我当前的代码:

async findOne(req, res){
        const { id } = req.params;
       await Prescriptions.
            findOne({ is_deleted: false, _id: id}).
             .populate(
               {
                 path: 'drugs',
                   populate: {
                     path: 'drugCateId',
                     model: 'DrugCategory'
                   }
               }).
            exec(function (err, data) {
              if (err) return handleError(err);
              res.send(data)
            });
      }

但这行不通。 以下是我的结果:

{
    "is_deleted": false,
    "_id": "5f32768a06693a520806717d",
    "patientId": "5c80930d447df7735138693e",
    "prescriptionName": "Prescription for you",
    "prescriptionNote": "Please drink follow doctor",
    "prescriptionDate": "2020-07-08T00:00:00.000Z",
    "diseaseId": "5f22a6d600980c081ca9e14f",
    "drugs": [
        {
            "_id": "5f32768a06693a5208067181",
            "drugcateId": "5f23deca04e3150a48632229", // How can I populate this one?
            "quantity": 10,
            "howtouse": "drink 2 times after meal everyday"
        },
        {
            "_id": "5f32768a06693a5208067180",
            "drugcateId": "5f23deca04e3150a48632233", // How can I populate this one?
            "quantity": 10,
            "howtouse": "drink 2 times after meal everyday"
        },
        {
            "_id": "5f32768a06693a520806717f",
            "drugcateId": "5f23deca04e3150a48632234", // How can I populate this one?
            "quantity": 10,
            "howtouse": "drink 2 times after meal everyday"
        },
        {
            "_id": "5f32768a06693a520806717e",
            "drugcateId": "5f23deca04e3150a4863224a", // How can I populate this one?
            "quantity": 10,
            "howtouse": "drink 2 times after meal everyday"
        }
    ],
    "createdBy": "5d1cd947231ceb95b8838c1b",
    "createdAt": "2020-08-11T10:44:26.842Z",
    "updatedAt": "2020-08-11T10:44:26.842Z",
    "__v": 0
}

希望你能理解我的问题,请看一下。谢谢你

【问题讨论】:

    标签: mongodb mongoose mongodb-query mongoose-schema mongoose-populate


    【解决方案1】:

    您似乎非常接近,但请确保提供正确的路径:

    .populate({
       path: 'drugcateId',
       model: 'DrugCategory'
    })
    

    drugCateId 更改为drugcateId

    此外,您应该能够直接填充DrugCategory

    【讨论】:

    • 是的,我有一个错误,我的模型是“drugcate”,但在我的填充命令中是“drugCate”。我已经将模型更改为“drugCate”,并且可以使用以下查询。 populate({ path: 'drugs.drugCateId', populate: {path: 'drugs.drugCateId'} }) 谢谢
    • 是的,这就是我所指出的。我不知道你为什么像这样嵌套人口。我的答案中的代码还不够吗?您是否尝试过以这种方式填充它 - 只需一个直接填充?
    【解决方案2】:

    您当前的版本与您的架构不匹配。它建议您同时填充drugsdrugs.drugcateId。但是这里drugs是直接嵌入的,而不是引用另一个集合中的文档,所以不可能populate()

     .populate({
         path: 'drugs',  // this assumes drugs are objectIds: [{ type: ObjectId, ref: 'Drug' }]
         populate: {
           path: 'drugCateId',
           model: 'DrugCategory'
         }
       })
    

    相反,您应该能够对数组使用点表示法:

    .populate({ path: "drugs.drugcateId" })
    

    或短

    .populate("drugs.drugcateId")
    

    【讨论】:

    • 是的,我有谢谢您的回复。我有一个错误,我的模型是“drugcate”,但在我的填充命令中是“drugCate”。我已经将模型更改为“drugCate”,并且可以使用以下查询。 ``` populate({ path: 'drugs.drugCateId', populate: {path: 'drugs.drugCateId'} }) ``` 谢谢
    【解决方案3】:

    感谢您的回复。我有一个错误,我的模型是“drugcate”,但在我的填充命令中是“drugCate”。我已经将我的模型更改为“drugCate”,并且可以使用以下查询。

    populate({ path: 'drugs.drugCateId', 
       populate: {path: 'drugs.drugCateId'}
    }) 
    

    谢谢

    【讨论】:

      猜你喜欢
      • 2012-01-22
      • 2016-09-15
      • 2017-05-21
      • 2018-12-28
      • 2019-07-28
      • 2021-07-09
      • 2020-11-21
      • 2019-01-31
      • 2013-07-06
      相关资源
      最近更新 更多