我正在尝试为用户添加评论API。我定义了一个不同的模型架构'userMessages',并使用userId作为架构'User'的引用。我试图发布路由进行评论,但收到验证错误,即使我已将userId和Comment String定义为true。
这是我的userMessages模式:
const userMessages = mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
userId: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true},
message: { type: String, required: true },
});
这是我添加消息的控制器:
exports.post_comment = (req, res, next) => {
let body = req.body;
body._id = mongoose.Types.ObjectId();
const userId = req.userData.user[0]._id;
body.userId = userId._id;
const commentSchema = new CommentSchema(body);
commentSchema.save()
.then(docs => {
console.log('user commented: ', docs);
res.status(201).json(docs);
})
.catch(err => {
console.log(err);
res.status(500).json(err);
})
}
当我尝试使用邮递员以“ userId和message”作为原始参数来打路由userMsg / comment时,出现以下错误:
{
"errors": {
"userId": {
"message": "Path `userId` is required.",
"name": "ValidatorError",
"properties": {
"message": "Path `userId` is required.",
"type": "required",
"path": "userId"
},
"kind": "required",
"path": "userId"
}
},
"_message": "UserMessages validation failed",
"message": "UserMessages validation failed: userId: Path `userId` is required.",
"name": "ValidationError"
}
即使将userID和message定义为TRUE,我也无法解决问题。
答案 0 :(得分:0)
错误在以下几行:
const userId = req.userData.user[0]._id;
body.userId = userId._id;
应该是:
const userId = req.userData.user[0]._id;
body.userId = userId;