Node.js+MongoDB社交平台创建Post报错排查求助
解决"Invalid value for schema path
user.type, got value 'undefined'"错误 你遇到的错误根源在Post模型文件里,有两个明显的语法错误,另外还需要验证请求中的用户ID是否正确传递:
1. 修正MongoDB ObjectId类型拼写错误
mongoose里的ObjectId类型首字母是大写的,你写的mongoose.Schema.Types.objectId是小写,导致mongoose无法识别这个类型,抛出user.type为undefined的错误。需要把所有objectId替换为ObjectId。
2. 修正模型导出语句错误
你的模型导出用了mongoose.export,这是错误的,正确的导出方式是module.exports。
修复后的post.js完整代码:
const mongoose = require('mongoose'); const postSchema = new mongoose.Schema({ media: { type: String, trim: true, required: true }, user: { type: mongoose.Schema.Types.ObjectId, ref: "User", required: true // 建议添加,确保帖子必须关联用户 }, likes: [ { type: mongoose.Schema.Types.ObjectId, ref: "Like" } ], comment: [ { type: mongoose.Schema.Types.ObjectId, ref: "Comment" } ] }, { timestamps: true, }); module.exports = mongoose.model("Post", postSchema);
3. 验证auth中间件的req.userId是否正确设置
确保你的auth中间件确实将用户ID赋值给了req.userId,并且这个值是有效的MongoDB ObjectId格式。示例auth中间件参考:
const jwt = require('jsonwebtoken'); const User = require('../models/user'); const auth = async (req, res, next) => { try { const token = req.header('Authorization')?.replace('Bearer ', ''); if (!token) { return res.status(401).json({ message: '缺少认证令牌' }); } const decoded = jwt.verify(token, process.env.JWT_SECRET); const user = await User.findById(decoded.id); if (!user) { throw new Error(); } req.userId = user._id; // 直接赋值ObjectId类型,mongoose会自动处理 next(); } catch (error) { res.status(401).json({ message: '认证失败,请重新登录' }); } }; module.exports = auth;
做完以上修改后,重新运行服务,创建帖子的请求应该就能正常执行了。
内容的提问来源于stack exchange,提问作者Advait Patole
相关产品推荐
相关产品推荐

