Mongoose .populate() 在Node.js应用中无法生效问题求助
Mongoose populate方法无法填充days数组的问题
各位好,这是我首次发帖!我遇到了Mongoose的populate方法完全不起作用的问题,以下是相关代码:
模型定义
Space模型
const spaceSchema = Schema( { user: { type: Schema.Types.ObjectId, required: true, ref: "User", }, name: { type: String, required: true, }, days: [{ type: Schema.Types.ObjectId, refPath: "Day" }], }, { versionKey: false, timestamps: true }, ); const Space = mongoose.model("Space", spaceSchema); module.exports = Space;
Day模型
const daySchema = Schema( { space: { type: Schema.Types.ObjectId, refPath: "Space" }, date: { type: String, required: true, }, water: { type: Boolean, }, fertilizer: { type: Boolean, }, transplant: { type: Boolean, }, comment: { type: String, }, }, { versionKey: false, timestamps: true }, ); const Day = mongoose.model("Day", daySchema); module.exports = Day;
控制器代码(/api/spaces/:id路由)
const getSpace = asyncHandler(async (req, res) => { const space = await Space.findById(req.params.id).populate("days"); res.status(200).json(space); });
当前返回结果
{ "_id": "63580115978dbf8f2f5a7a50", "user": "63501ab84613855834daa4ef", "name": "spaceName", "days": [] }
我尝试了多种方法,但结果始终如此。期望返回的结果应包含days数组的具体文档数据,示例如下:
{ "space": { "_id": "63580115978dbf8f2f5a7a50", "user": "63501ab84613855834daa4ef", "name": "spaceName", "days": [ { "_id": "63581af565aed8cad3210046", "space": "63580115978dbf8f2f5a7a50", "date": "29/10/2022", "water": true, "fertilizer": true, "transplant": false, "comment": "This is a comment.", "createdAt": "...", "updatedAt": "..." }, { "_id": "63581af565aed8cad3210046", "space": "63580115978dbf8f2f5a7a50", "date": "29/10/2022", "water": false, "fertilizer": false, "transplant": true, "comment": "This is a comment.", "createdAt": "...", "updatedAt": "..." } ] } }
若需要其他代码片段,请告知,感谢大家的帮助!
解决方案
问题出在refPath的错误使用上:refPath是用于动态关联不同模型的场景,而你这里是固定关联Day和Space模型,应该直接使用ref字段。
1. 修改模型定义
- Space模型:将
days字段的refPath改为ref
days: [{ type: Schema.Types.ObjectId, ref: "Day" }],
- Day模型:将
space字段的refPath改为ref
space: { type: Schema.Types.ObjectId, ref: "Space" },
2. 额外验证
- 确认Day集合中存在关联的文档,且其
space字段值与目标Space的_id完全匹配 - 确认创建Space时,已将对应的Day文档
_id正确添加到days数组中
修改后重新调用接口,populate("days")就能正常填充数组内容了。
内容的提问来源于stack exchange,提问作者JOlle11
相关产品推荐
相关产品推荐

