简体   繁体   English

为什么 mongoose 错误 object 中没有消息?

[英]Why is there no message in mongoose error object?

I am making a user signup API, where name and email are set to be unique.我正在进行用户注册 API,其中名称和 email 设置为唯一。 When I send a JSON object which has a the same email address as an existing user, it gives an error as expected.当我发送与现有用户具有相同 email 地址的 JSON object 时,它会按预期给出错误。 But there is no message in that error , which i can then use to give a more usable message.但是该错误中没有任何消息,然后我可以使用它来提供更有用的消息。

Below is the error object that i'm getting.下面是我得到的错误 object。

{ "index": 0,    
 "code": 11000,
 "keyPattern": {
    "email": 1
},
 "keyValue": {
    "email": "pranatkarode@rocketmail.com"
 }
}

And this is my controller module,这是我的 controller 模块,

const User=require("../models/userModels.js");
exports.signUp=(req,res)=>{
const user=new User(req.body);
user.save((err,user)=>{
    if(err){
        res.send(err)
    }
    else{
        res.json({
            user
        })
    }
})
}

Mongoose's default error object is designed for non limited use cases. Mongoose 的默认错误 object 专为非受限用例而设计。 So you need to look at it and depending on what it contains add custom messages.因此,您需要查看它并根据它包含的内容添加自定义消息。 For this specific use case of yours, you can for example do it like so:对于您的这个特定用例,您可以例如这样做:

const User = require("../models/userModels.js");
exports.signUp = async (req, res) => {
  try {
    const user = new User(req.body);
    await user.save();
    res.json({
      user,
    });
  } catch (err) {
    if (err.code === 11000 && err?.keyPattern.hasOwnProperty("email")) {
      err.message = "This email is alrady used.";
    } else if (err.code === 11000 && err?.keyPattern.hasOwnProperty("name")) {
      err.message = "This name is alrady taken.";
    }
    res.send(err);
  }
};

I'm using async / await syntax here to have a better looking code, yours would work as well.我在这里使用async / await语法来获得更好看的代码,你的也可以。

I would suggest to wrap an await/async try/catch block to your method and to check if you are getting anything from req.body before trying to save to the database:我建议将 await/async try/catch 块包装到您的方法中,并在尝试保存到数据库之前检查您是否从 req.body 获得任何内容:

    exports.signUp = async (req,res)=>{
      try { 
        const user=new User(req.body);
        if (!user) throw new Error("Your message ...");
        user.save();
        // res.status(201).json(user);
      } catch {
        res.status(422).json({ message: err.message ?? err });
      }
    }

The solution is quite simple,just remove the await before the await user.save and boom everything should be fine... but if problem persist then check your username and password in ur.env file and make sure they are correct, also you should make sure ur ip address is set to both 0.0.0.0 and ur current ip in the atlas.解决方案非常简单,只需在 await user.save 之前删除 await 并繁荣一切都应该没问题...但是如果问题仍然存在,请检查 ur.env 文件中的用户名和密码并确保它们正确,你也应该确保您的 ip 地址在地图集中设置为 0.0.0.0 和您当前的 ip。 before = await user.save();之前 = 等待 user.save(); after = user.之后=用户。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM