Mongoose StrictPopulateError求助:无法填充influencerimg路径
解决Mongoose StrictPopulateError报错问题
报错信息
StrictPopulateError: Cannot populate path
influencerimgbecause it is not in your schema. Set thestrictPopulateoption to false to override.
at getModelsMapForPopulate (E:\React-Live\socialinfluencer\server\node_modules\mongoose\lib\helpers\populate\getModelsMapForPopulate.js:49:12)
问题原因
报错核心是你在populate时指定的路径influencerimg不存在于imageUploadSchema中。你的imageUploadSchema里关联influencerimg模型的字段是image数组,所以正确的populate路径应为image,而非influencerimg。
另外代码存在两处小问题:
- 定义
ImgSchema时未正确引入Schema(直接用了new Schema()但未从mongoose解构) getImage接口里存在拼写错误:fetced应为fetched
修复后的完整代码
模型文件(userUpload.js)
const mongoose = require("mongoose"); const { Schema } = mongoose; const imageUploadSchema = new Schema({ user: { type: Schema.Types.ObjectId, required: true, // 修正为布尔值true,而非字符串"true" }, image: [{ type: Schema.Types.ObjectId, ref: "influencerimg", }], }); exports.imageUpload = mongoose.model("image-upload", imageUploadSchema); // 图片模型 const ImgSchema = new Schema({ bio: String, image: String, }); exports.influencerimg = mongoose.model('influencerimg', ImgSchema);
控制器文件
const model = require("../model/userUpload"); const imageUpload = model.imageUpload; exports.uploadImage = async (req, res) => { const { user, image } = req.body; try { const alreadyExist = await imageUpload.findOne({ user }); console.log(alreadyExist, 'alreadyExist'); if (alreadyExist) { // 添加{ new: true }返回更新后的文档(可选优化) const updateimgId = await imageUpload.findOneAndUpdate( { user }, { $push: { image } }, { new: true } ); if (updateimgId) { return res.status(200).json({ success: 1, message: 'Image ID uploaded successfully' }); } } else { const createNewById = new imageUpload({ user, image }); await createNewById.save(); return res.send({ code: 200, message: "Image added successfully" }); } } catch (error) { console.log(error); return res.status(500).json({ message: 'Internal Server Error' }); } }; exports.getImage = async (req, res) => { try { // 修正populate的path为正确的字段名image const data = await imageUpload.findOne({ user: req.params.user }).populate({ path: 'image', select: 'image' }); if (data) { return res.status(200).json({ message: 'Data fetched successfully', data: data }); } else { // 数据不存在应返回404状态码,而非500 return res.status(404).json({ message: 'Data not Found' }); } } catch (error) { console.log(error); return res.status(500).json({ message: 'Internal Server Error' }); } };
额外说明
- 移除了
strictPopulate: false选项:因为路径修正后符合schema定义,不再需要该选项绕过校验 - 将
required: "true"改为required: true:符合Mongoose的参数规范 uploadImage中添加{ new: true }:让findOneAndUpdate返回更新后的文档(如果需要获取更新后的数据)getImage中把500状态码改为404:数据不存在属于客户端请求的资源不存在,对应HTTP 404状态码更规范
内容的提问来源于stack exchange,提问作者Vasim Shaikh
相关产品推荐
相关产品推荐

