Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
744 views
in Technique[技术] by (71.8m points)

mongoose - how to retrieve the error object in the mongodb duplicate error

I am working with nodejs and mongoose to store the user information as showed in the code

  const User = mongoose.model('User')
  let user = new User(req.body);

   user.save(function (error) {
    if (error) {
      switch(error.code){
          case 11000:
            console.log('error', 'User already exists 11000',error);
            console.log(error.code, error.name,error.index,error.driver);
            return res.status(422).send({
              error: error
            });
      }
   }

when it comes to store the duplicated objects in mongodb, it will throw out an exception with code 11000. The code above can capture this exception with error object.

In the debugging, the code line console.log('error', 'User already exists 11000',error); below will output an error message like the one below

{ MongoError: E11000 duplicate key error collection: game-dev.users index: email_1 dup key: { : "[email protected]" }
at Function.create 
 ......

this error message is useful however it doesn't exist in the error object - user.save(function (error). the error object only has [ 'driver', 'name', 'index', 'code' ] keys.

my question is how can i retrieve this error message?

question from:https://stackoverflow.com/questions/66052376/how-to-retrieve-the-error-object-in-the-mongodb-duplicate-error

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

First, you can find the data with a unique key. if data found then return error else add data to DB

const User = mongoose.model('User');
 const is_user=User.findOne({email_1 :req.body.email_1});
 if(is_user){
    return res.status(400).json({
            message: "User aready exist with this email address"});
          }else{
  let user = new User(req.body);
    user.save();
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...