如何在插入违反唯一索引的MongoDB文档时捕获错误? [英] How to catch the error when inserting a MongoDB document which violates an unique index?

查看:240
本文介绍了如何在插入违反唯一索引的MongoDB文档时捕获错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个MEAN应用程序。

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 ::引起的:: 11000 E11000重复键
错误索引:

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

有人可以解释如何,而不是错误发送json像 {succes:false,message:'User already exists!'}

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.

推荐答案

您将需要测试保存方法返回的错误,以查看是否为重复的用户名引发了错误。

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(500).send({ succes: false, message: 'User already exist!' });
      }

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

    res.json({
      success: true
    });

  });
})

这篇关于如何在插入违反唯一索引的MongoDB文档时捕获错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆