node.js - mongoose E11000 duplicate key error collection

查看:365
本文介绍了node.js - mongoose E11000 duplicate key error collection的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

mongoDB 插入数据时,第一条数据能插入,第二条提示E11000 duplicate key error collection。怎么解决?

user.js

const mongoose = require('mongoose');

const Schema = mongoose.Schema;

// create Comment Schema & model
const UserSchema = new Schema({
    uid: {
        type : Number,
        index: {
            unique: true
        },
    },
    username: {
        type: String,
        required: [true, 'username field is required']
    },
    password: {
        type: String,
        required: [true, 'username field is required']
    },
    headImageUrl: {
        type: String,
    },
    created: {
        type: Date,
        default: Date.now
    },
    admin: {
        type: Boolean,
        default: false
    }


});

const User = mongoose.model('users', UserSchema);

module.exports = User;

插入数据库部分的代码:

router.post('/regeist', function (req, res, next) {
    bcrypt.hash(req.body.password, config.saltRounds).then(function (hashPassword) {
        req.body.password = hashPassword;
        User.create(req.body).then(function (echo) {
            res.json(echo);
        }).catch(next);
    });
});

错误信息:

WriteError({"code":11000,"index":0,"errmsg":"E11000 duplicate key error collection: video.users index: id_1 dup key: { : null }","op":{"username":"Fcho","password":"$2a$10$0SQsBRvqaRC8JB37dMWEMegGvScsce3YosG9QwoLeL1s0KcQq0HMW","uid":10001,"_id":"5985df9c05e88c2272d79745","admin":false,"created":"2017-08-05T15:09:16.908Z","__v":0}})

解决方案

报错的原因

数据值重复。

你设置了一个 uid 的字段,但是第一次插入数据表的时候,你没有赋值,uid 字段是 null。第二次再插入数据的时候,uid 还是没有赋值,字段还是 null,而且你还设置 uid 属性是 unique,两次的数据都是 null ,所以报错了。

解决办法

uid 这个字段是不需要设置的,MongoDB 数据库会自动给每一条记录设置一个 ObjectId
下面这一部分去掉就行了:

uid: {
        type : Number,
        index: {
            unique: true
        },
    },

这篇关于node.js - mongoose E11000 duplicate key error collection的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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