【问题标题】:Fixing validation error for defined schema in node js修复节点 js 中已定义模式的验证错误
【发布时间】:2019-01-10 20:07:53
【问题描述】:

我正在尝试为用户添加评论 API。我定义了一个不同的模型模式“userMessages”并使用 userId 作为模式“用户”的参考。我尝试发布路由以供评论,但收到验证错误,即使我已将 userId 和 Comment String required 定义为 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 和消息”作为我的原始正文参数来点击路由 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,我也无法找出问题所在。

【问题讨论】:

    标签: javascript node.js express


    【解决方案1】:

    错误在以下几行:

    const userId = req.userData.user[0]._id;
    body.userId = userId._id;
    

    应该是:

    const userId = req.userData.user[0]._id;
    body.userId = userId;
    

    【讨论】:

    • 非常感谢。有效!我犯了这样的错误真是太菜鸟了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-31
    • 1970-01-01
    • 2018-10-21
    • 2021-10-17
    • 2018-07-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多