Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to catch the error when inserting a MongoDB document which violates an unique index?

I'm building a MEAN app.

This is my Username schema, the username should be unique.

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

module.exports = mongoose.model('User', new Schema({ 
    username: { type: String, unique: true }
}));

On my post route I save the user like this:

app.post('/authenticate', function(req, res) {
        var user = new User({
            username: req.body.username
        });

        user.save(function(err) {
            if (err) throw err;

            res.json({
                success: true
            });

        });
    })

If I post with the same username again I get this error:

MongoError: insertDocument :: caused by :: 11000 E11000 duplicate key error index:

Can someone explain how instead of the error to send a json like { succes: false, message: 'User already exist!' }

Note: After I post the user I will automatically authentificate, dont need password or something else.

like image 241
Hiero Avatar asked Jun 02 '15 10:06

Hiero


People also ask

How to make sure a field is unique in MongoDB?

To create a unique index, use the db. collection. createIndex() method with the unique option set to true .

How do I avoid duplicate errors in MongoDB?

If you ever faced this error all you need to do is to check your model carefully and find out that is there any unique key set true by you and if it is not necessary then simply remove the unique key from the model or otherwise set a unique value if it is necessary to be unique.

What does __ V mean in MongoDB?

The “_v” field in Mongoose is the versionKey is a property set on each document when first created by Mongoose. This key-value contains the internal revision of the document. The name of this document property is configurable.


2 Answers

You will need to test the error returned from the save method to see if it was thrown for a duplicative username.

app.post('/authenticate', function(req, res) {
  var user = new User({
    username: req.body.username
  });

  user.save(function(err) {
    if (err) {
      if (err.name === 'MongoError' && err.code === 11000) {
        // Duplicate username
        return res.status(422).send({ succes: false, message: 'User already exist!' });
      }

      // Some other error
      return res.status(422).send(err);
    }

    res.json({
      success: true
    });

  });
})
like image 84
Jason Cust Avatar answered Sep 23 '22 11:09

Jason Cust


You can also try out this nice package mongoose-unique-validator which makes error handling much easier, since you will get a Mongoose validation error when you attempt to violate a unique constraint, rather than an E11000 error from MongoDB:

var mongoose = require('mongoose');
var uniqueValidator = require('mongoose-unique-validator');

// Define your schema as normal.
var userSchema = mongoose.Schema({
    username: { type: String, required: true, unique: true }
});

// You can pass through a custom error message as part of the optional options argument:
userSchema.plugin(uniqueValidator, { message: '{PATH} already exists!' });
like image 30
chridam Avatar answered Sep 23 '22 11:09

chridam