简体   繁体   English

尝试通过动态选择 model 与 mongoose 一起使用来填充对象数组中每个 object 中的单个字段

[英]trying to populate a single field in each object inside an array of objects by dynamically picking the model to use with mongoose

I'm trying to use refPath to reference which collection to pull the population data from inside my schema, and even though it looks identical to the examples I've seen, its just not working.我正在尝试使用 refPath 来引用哪个集合从我的架构中提取人口数据,即使它看起来与我看到的示例相同,但它只是不起作用。

Here is my schema for statesPersons, not super important, but it contains the activeWork array of objects.这是我的 statesPersons 模式,不是特别重要,但它包含对象的 activeWork 数组。

import mongoose, {model, Schema}  from "mongoose";

const statesPersonsSchema = new Schema(
  {
    profileId: {
      type: String,
      required: true,
      unique: true,
    },
    department: {
      type: String,
      required: true,
      index: true,
    },
    firstName: String,
    lastName: String,
    location: String,
    org: String,
    title: String,
    jobDescription: String,
    email: {
      type: String,
      lowercase: true,
    },
    phoneNumber: String,
    activeWork: ["activeWork"],
    emailList: [String],
    jobAssignments: [String],
    affiantInfo: {
      affiantInfoTitle: String,
      affiantInfoExperience: String,
    },
    assessments: [
      {
        assessdBy: {
          type: Schema.Types.ObjectId,
          ref: "statesPerson",
        },
        dueDate: Date,
        questions: {},
      },
    ],
  },
  { strictPopulate: false }
);



export default mongoose.model("statesPersons", statesPersonsSchema);

Here is my schema for activeWork, the array of objects.这是我的 activeWork 模式,对象数组。 This has the referenceId that I need to populate as well as the collectionType which I pull what collection it is from.这具有我需要填充的 referenceId 以及我从中提取它的集合的 collectionType。

import mongoose, {model, Schema}  from "mongoose";

const activeWorkSchema = new Schema(
  {
    active: Boolean,
    collectionType: {
      type: String,
      enum: ["messages", "cases"],
    },
    referenceId: {
      type: Schema.Types.ObjectId,
      refPath: "collectionType",
    },
    sentBy: {
      type: Schema.Types.String,
      ref: "statesPersons",
    },
    sentTo: {
      type: Schema.Types.String,
      ref: "statesPersons",
    },
    timeRecived: Date,
    dueDate: Date,
    subject: String,
    viewed: Boolean,
    content: {},
  },
  { strictPopulate: false }
);

  export default mongoose.model("activeWork", activeWorkSchema);

And here is my query.这是我的查询。

export async function getStatesPersonsActiveWorkByProfileId(req, res){
    mongoose.set('debug', true);
    try{
        const { profileId } = req.params

        const data = await statesPersons
        .find({ profileId })
        .populate('statesPersons.activeWork.referenceId')
        .exec()
        
        return res.send({
            message: "success",
             data: data,
             status: 200 })
    }catch(e) {
        console.error(e.message)
        return res.send({
            message: "couldn't fetch active work",
             data: null,
             status: 500 })
    }
}

its returning with the statesPersons object and the activeWork contains the objectId I need to populate, but its not populating.它返回 statesPersons object 并且 activeWork 包含我需要填充的 objectId,但它没有填充。 it looks like this.它看起来像这样。

"activeWork": [
                {
                    "active": true,
                    "collectionType": "messages",
                    "referenceId": "63a49e3052658ce60c1dafcb",
                    "sentBy": "108416469928574003772",
                    "dueDate": "2018-02-21T11:16:50.362Z",
                    "subject": "testing",
                    "viewed": false,
                    "_id": "63a49e3052658ce60c1dafce"

I can force it to work by changing the query to be explicit.我可以通过将查询更改为显式来强制它工作。


        const data = await statesPersons
        .find({ profileId })
        .populate({path: 'activeWork.referenceId', model: 'messages'})
        .exec()
        

which looks like this.看起来像这样。

activeWork": [
            {
                    "active": true,
                    "collectionType": "messages",
                    "referenceId": {
                        "_id": "63a49e3052658ce60c1dafcb",
                        "involvedParties": [
                            "108416469928574003772",
                            "100335565301468600000"
                        ],
                        "comments": [
                            {
                                "sender": [
                                    "108416469928574003772"
                                ],
                                "dateSent": "2022-12-22T18:13:04.604Z",
                                "content": "There is no way this is going to work.",
                                "_id": "63a49e3052658ce60c1dafcc"
                            }
                        ],

But this wont work because I need it to be able to pull what model to use from the collectionType field但这行不通,因为我需要它能够从 collectionType 字段中提取要使用的 model

sorry for the late response, it seems like you are trying to populate the multilevel documents multilevel population .抱歉回复晚了,您似乎正在尝试填充多级文档multilevel population

here is an example.这是一个例子。

db.statesPersonsSchema.find({ profileId }). populate({
    path: 'activeWorkSchema',
    populate: { path: 'referenceId' }
  });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM