我有一个这样的MongoDb模式

    var User = new Schema({
    "UserName": { type: String, required: true },
    "Email": { type: String, required: true, unique: true },
    "UserType": { type: String },
    "Password": { type: String }
});

我正在try 创建一个新用户

    controller.createUser = function (req, res) {

    var user = new models.User({
        "UserName": req.body.UserName.toLowerCase(),
        "Email": req.body.Email.toLowerCase(),
        "UserType": req.body.UserType.toLowerCase()
    });
    models.User.findOne({ 'Email': user.Email }, function (err, olduser) {
                    if (!err) {
                        if (olduser) {
                            res.send({ 'statusCode': 409, 'statusText': 'Email Already Exists' });
                        }
                        else if (!olduser) {
                            user.setPassword(req.body.Password);
                            user.save(function (err, done) {
                                if (!err) {
                                    console.log(user);
                                    res.send({ 'statusCode': 201, 'statusText': 'CREATED' });
                                }
                                else {
                                    res.send({ 'Status code': 500, 'statusText': 'Internal Server Error' });
                                }
                            });
                        }
                    }
                    else {
                        res.send({ 'statusCode': 500, 'statusText': 'ERROR' });
                    }
                });
};

为了创建新用户,我给出了如下属性和值:

 {
"UserName": "ann",
"Email": "ann@ann.com",
"UserType": "normaluser",
"Password":"123456"
}

我得到了这样的错误:

{"Status code":500,"statusText":"Internal Server Error","Error":{"name":"MongoError","err":"E11000 duplicate key error index: medinfo.users.$UserName_1  dup key: { : \"ann\" }","code":11000,"n":0,"connectionId":54,"ok":1}}

我知道这个错误是因为用户名是重复的,但是I haven't set UserName with unique constraint.Whenever I add a new row,I need only email to be unique,UserName can be repeated.如何做到这一点??

推荐答案

@ManseUK可能是对的,看起来用户名是一个"键"——在本例中是一个索引._id属性是默认情况下创建的"主要"索引,但mongodb允许您拥有多个索引.

启动mongo控制台并运行medinfo.users.getIndexes()?一定是什么东西在"用户名"上添加了索引.

required: true不会这么做,但你以前可能玩过其他设置,但索引没有被删除?

Mongodb相关问答推荐

会话的Mongo-go驱动程序版本.Copy()

在MondoDB中:将对象数组从切片索引数组切片,并通过聚合推入数组

如何将空值单独分组?

使用MongoDB 4将根文档替换为数组

来自嵌套对象数组的 MongoDB 聚合

通过insertId MongoDB获取文档

如何在 MongoDB 中已经存在的 slug 中添加一个随机数?

从 kubectl exec 获取返回值到 powershell 脚本

使用名为 Object 键的 uuid 创建 mongodb 文档

TypeError:Cannot read property '_id' of undefined

Pymongo API TypeError: Unhashable dict

具有最佳插入/秒性能的数据库?

用 Redis 查询?

将数据插入 MongoDB - 没有错误,没有插入

如何知道 MongoDB 集合大小?

MongoDB - 我如何找到另一个集合中的文档未引用的所有文档

MongoDB Compass 过滤器(查询)

如何在 MongoDB 的 $match 中使用聚合运算符(例如 $year 或 $dayOfMonth)?

MongoDB 按数组元素对文档进行排序

mongo dbname --eval 'db.collection.find()' 不起作用