【问题标题】:Mongoose Throw Error When Non Existing Key is Present不存在的键存在时 Mongoose 抛出错误
【发布时间】:2021-04-16 17:15:11
【问题描述】:

我有一个代码,我正在使用请求正文更新我的架构对象。我已经在架构上应用了验证规则。问题是,当请求正文中存在不存在的字段时,我希望架构抛出错误。不存在的键不会按我的意愿保存到数据库中,但我想抛出一些错误而不是保存对象。架构:

const peopleSchema = new mongoose.Schema(
    {
        fullname: {
            type: String,
            required: [true, "fullname is required"],
            validate: [(value) => isAlpha(value, "en-US", {ignore: " "}), "name should be alphabetic only"],
        },
        phone: {
            type: String,
            validate: [isPhone, "please enter a valid phone number"],
        },
        address: String,
    },
    { timestamps: true }
);

更新人的代码:

router.put("/:id", checkUser, async (req, res, next) => {
    try {
        const { id } = req.params;
        const user = req.currentUser;
        const person = user.people.id(id);
        
        person.set(req.body);

        const response = await user.save();
        res.json({ response });
    } catch (err) {
        next(new BadRequestError(err));
    }
});

【问题讨论】:

  • 如果问题没有解决,请留言,如果解决接受我的回答,谢谢
  • @MohammadYaserAhmadi 好的,当我测试它时,我会继续。谢谢。
  • 如果您的问题解决了,请接受我的回答
  • @MohammadYaserAhmadi,它没有用。但我照原样做。忽略多余的字段并保存记录。

标签: javascript node.js validation mongoose


【解决方案1】:

验证有两种基于 callbackasync 的方法, 因为您的代码基于 async/await,所以您必须使用 validateSync(),如下代码:

let errors = user.validateSync()//check validation
if(errors){
     console.log(errors)
     throw errors;//handle your error 
     }
const response =  await user.save()

在回调方法中:

 user.save(function(err,response){ 
    if (err){ 
        console.log(err); 
        //handle error
       } 
     else{ 
         console.log(response) 
         res.json({ response });
      } 
 })

【讨论】:

    猜你喜欢
    • 2015-06-11
    • 1970-01-01
    • 1970-01-01
    • 2023-01-31
    • 1970-01-01
    • 2021-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多