开发者社区> 问答> 正文

在mongodb中保存第二条数据时报错E11000 duplicate key ?400报错

{ BulkWriteError: E11000 duplicate key error collection: anomaly_monitoring.users index: name_1 dup key: { : null }
    at F:\github-workspace\anomaly-monitoring\server-koa2\node_modules\mongodb\lib\bulk\unordered.js:535:15
    at handleCallback (F:\github-workspace\anomaly-monitoring\server-koa2\node_modules\mongodb\lib\utils.js:128:55)
    at resultHandler (F:\github-workspace\anomaly-monitoring\server-koa2\node_modules\mongodb\lib\bulk\unordered.js:456:5)
    at F:\github-workspace\anomaly-monitoring\server-koa2\node_modules\mongodb-core\lib\connection\pool.js:541:18
    at _combinedTickCallback (internal/process/next_tick.js:131:7)
    at process._tickCallback (internal/process/next_tick.js:180:9)
  name: 'BulkWriteError',
  message: 'E11000 duplicate key error collection: anomaly_monitoring.users index: name_1 dup key: { : null }',
  driver: true,
  code: 11000,
  index: 0,
  errmsg: 'E11000 duplicate key error collection: anomaly_monitoring.users index: name_1 dup key: { : null }',
  getOperation: [Function],
  toJSON: [Function],
  toString: [Function],
  result:
   BulkWriteResult {
     ok: [Getter],
     nInserted: [Getter],
     nUpserted: [Getter],
     nMatched: [Getter],
     nModified: [Getter],
     nRemoved: [Getter],
     getInsertedIds: [Function],
     getUpsertedIds: [Function],
     getUpsertedIdAt: [Function],
     getRawResponse: [Function],
     hasWriteErrors: [Function],
     getWriteErrorCount: [Function],
     getWriteErrorAt: [Function],
     getWriteErrors: [Function],
     getLastOp: [Function],
     getWriteConcernError: [Function],
     toJSON: [Function],
     toString: [Function],
     isOk: [Function] } }

上面这是报错信息,下面贴我的代码

先是链接数据库

connect()
mongoose.connection
  .on('error', console.log)
  .on('disconnected', connect)
  .once('open', listen)


function listen () {
  app.listen(config.port, () => {
    console.log('%s BackEnd Server is running on: http://%s:%s', config.appName, config.host, config.port)
  })
}
// 数据库连接
function connect () {
  mongoose.Promise = global.Promise
  return mongoose.connect('mongodb://' + config.database.host + '/' + config.database.db)

然后是model

/**
 * Created by pc on 2018/3/8.
 */
const mongoose = require('mongoose')
const bcrypt = require('bcryptjs')
const SALT_WORK_FACTOR = 10

const UserSchema = new mongoose.Schema({
  'userName': {
    unique: true,
    type: String
  },
  'password': String,
  'role': {
    type: Number,
    default: 0 //0普通用户,1管理员
  },
  'createAt': {
    type: Date,
    default: Date.now()
  },
  'updateAt': {
    type: Date,
    default: Date.now()
  }
})

UserSchema.pre('save', function (next) {
  var user = this
  if (this.isNew) {
    this.createAt = this.updateAt = Date.now()
  } else {
    this.updateAt = Date.now()
  }

  bcrypt.genSalt(SALT_WORK_FACTOR, function (err, salt){
    if (err) return next(err)
    bcrypt.hash(user.password, salt, function (err, hash) {
      if (err) return next(err)
      user.password = hash
      next()
    })
  })
})

UserSchema.methods = {
  comparePassword: async function (password){
    try {
      return await bcrypt.compare(password, this.password)
    } catch (e) {
      console.log(e)
    }
  }
}

UserSchema.statics = {
  fetch: function () {
    return this
      .find({})
      .sort('updateAt')
      .exec()
  },
  findById: function (id){
    return this
      .findOne({_id: id})
      .exec()
  }
}

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

module.exports = User

下面是用户注册,注册第一条数据没问题,第二条就开始报错

/**
 * Created by pc on 2018/3/7.
 */

const User = require('../models/user')
// User.remove({},function(){
//   console.log(123)
// })
// User.find({},function(err,doc){
//   console.log(doc)
// })
// 用户注册
exports.register = async function (ctx){
  let _user = ctx.request.body
  const {userName, password, role, cipher} = ctx.request.body
  console.log(_user)
  try {
    if(_user.role){
      if( _user.cipher !== _user.userName + '666'){
        return ctx.resJson(4)
      }
    }
    console.log(222, _user)
    let oldUser = await User.findOne({userName: _user.userName})
    if (oldUser) {
      return ctx.resJson(1)
    } else {
      let user = new User({
        userName,
        password,
        role
      })
      console.log(333, user)
      await user.save()
      return ctx.resJson({redirectTo: '/login'})
    }
  } catch (e){
    console.log(111, e)
  }
}

// 用户登录
exports.login = async function (ctx) {
  const {userName,password} = ctx.request.body
  
  try{
    let user = await User.findOne({userName: userName})
    if (!user){
      return ctx.resJson(2)
    }
    let isMatch = await user.comparePassword(password)
    if (isMatch){
      ctx.session.user = user
      return ctx.resJson()
    } else{
      return ctx.resJson(3)
    }
  } catch (e){
    console.log(e)
  }
}

// 登出
exports.logout = function (ctx) {
  delete ctx.session.user
  return ctx.resJson()
}

// 用户列表
exports.userList = async function (ctx) {
  try {
    let users = await User.fetch()
    return ctx.resJson(users)
  } catch (e) {
    console.log(e)
  }
}

展开
收起
爱吃鱼的程序员 2020-06-07 17:44:13 947 0
1 条回答
写回答
取消 提交回答
  • https://developer.aliyun.com/profile/5yerqm5bn5yqg?spm=a2c6h.12873639.0.0.6eae304abcjaIB
                        <p><code>由于独特的约束,MongoDB只会允许一个文件,缺少索引字段。如果有一个以上的文档没有索引字段的值或缺少索引字段就会报错</code></p>
    

    自己手动添加id值,当插入的数据带有_id的字段时,mongodb就不再自动生成id。
    至此问题解决。

                            可我打印mongodb自动生成的ID并没有重复,昨天最后我把我的代码在同事的电脑上跑没问题,我就把我电脑上的mongodb卸载了,安了个最新版本就好了,但之前在我电脑上跑别的代码,一样的保存方式并没有问题。谢谢啦,兄弟
    
    2020-06-07 17:44:32
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
开源数据库 MongoDB 专场 MongoDB疑难杂症分析及优化 立即下载
MongoDB多数据中心的方案选型之路 立即下载
饿了么高级架构师陈东明:MongoDB是如何逐步提高可靠性的 立即下载