使用Mongoose refPath动态填充数组对象字段失败问题排查
Mongoose refPath动态填充失效问题
我尝试在Mongoose Schema中使用refPath指定填充数据的集合,写法与官方示例一致,但填充功能无法正常工作。手动指定model时填充可正常执行,但这种方式无法满足根据collectionType动态选择model的需求。
statesPersons Schema(包含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);
activeWork Schema(包含需填充的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);
查询代码
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 }) } }
问题现象
返回结果中,statesPersons对象的activeWork仅保留需要填充的ObjectId,未完成填充:
"activeWork": [ { "active": true, "collectionType": "messages", "referenceId": "63a49e3052658ce60c1dafcb", "sentBy": "108416469928574003772", "dueDate": "2018-02-21T11:16:50.362Z", "subject": "testing", "viewed": false, "_id": "63a49e3052658ce60c1dafce" } ]
可行但不符合需求的写法
手动指定model时填充可正常工作,但无法动态切换集合:
const data = await statesPersons .find({ profileId }) .populate({path: 'activeWork.referenceId', model: 'messages'}) .exec()
内容的提问来源于stack exchange,提问作者Nick Woffard
相关产品推荐
相关产品推荐

