MongoDB使用Mongoose populate关联查询数组ID遇CastError问题
问题:Mongoose populate关联查询时出现CastError且无法返回完整Post信息
我有一个Popular Mongoose模型,其中PopularPosts数组存储Post模型的ObjectId,存储操作正常,但GET请求时该数组只返回ID,尝试用populate关联查询获取完整Post详情时出现CastError。相关代码及错误信息如下:
Popular模型
const mongoose = require('mongoose'); const PopularSchema = new mongoose.Schema( { PopularPosts: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Post', required: false, }], createdAt: { type: Date, default: Date.now, } }, { timestamps: true } ); module.exports = mongoose.model("Popular", PopularSchema);
Post模型
const mongoose = require('mongoose'); const PostSchema = new mongoose.Schema( { title: { type: String, required: true, }, img: { type: String, required: true, }, category: { type: mongoose.Schema.Types.ObjectId, ref: "Category", }, desc: { type: String, required: false, }, createdAt: { type: Date, default: Date.now, } }, { timestamps: true } ); module.exports = mongoose.model("Post", PostSchema);
查询代码
const Popular = require('../../models/Popular'); class FindPopularPosts { async find(req, res) { const { id } = req.params; try { const popularPosts = await Popular.findById({id}).populate({ path: 'PopularPosts', model: 'Post', }).lean(); return res.status(200).json(popularPosts); } catch (err) { return res.status(500).json(err); } } } module.exports = new FindPopularPosts();
Postman错误信息
{ "stringValue": "\"{ id: '63b5a895fbb93698183d75d2' }\"", "valueType": "Object", "kind": "ObjectId", "value": { "id": "63b5a895fbb93698183d75d2" }, "path": "_id", "reason": {}, "name": "CastError", "message": "Cast to ObjectId failed for value \"{ id: '63b5a895fbb93698183d75d2' }\" (type Object) at path \"_id\" for model \"Popular\"" }
问题解决
错误原因
Popular.findById({id})的参数传递错误:findById()方法接受的是单个ObjectId字符串值,而不是一个包含id属性的对象。你传入的{id}会被Mongoose当作要转换为ObjectId的值,自然触发CastError。
修正后的查询代码
将findById({id})改为findById(id)即可:
const Popular = require('../../models/Popular'); class FindPopularPosts { async find(req, res) { const { id } = req.params; try { const popularPosts = await Popular.findById(id).populate({ path: 'PopularPosts', model: 'Post', }).lean(); return res.status(200).json(popularPosts); } catch (err) { return res.status(500).json(err); } } } module.exports = new FindPopularPosts();
验证说明
修正后,Mongoose会正确将id参数当作ObjectId查询Popular文档,同时通过populate('PopularPosts')关联查询出对应的完整Post数据,返回的PopularPosts数组不再是单纯的ID,而是包含所有Post字段的对象。
内容的提问来源于stack exchange,提问作者Routfin
相关产品推荐
相关产品推荐

