在mongodb中保存第二条数据时报错E11000 duplicate key ?400报错-问答-阿里云开发者社区-阿里云

开发者社区> 问答> 正文

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

爱吃鱼的程序员 2020-06-07 17:44:13 22
{ 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)
  }
}
NoSQL 数据库连接 MongoDB 数据库
分享到
取消 提交回答
全部回答(1)
  • 爱吃鱼的程序员
    2020-06-07 17:44:32
                        <p><code>由于独特的约束,MongoDB只会允许一个文件,缺少索引字段。如果有一个以上的文档没有索引字段的值或缺少索引字段就会报错</code></p>
    

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

                            可我打印mongodb自动生成的ID并没有重复,昨天最后我把我的代码在同事的电脑上跑没问题,我就把我电脑上的mongodb卸载了,安了个最新版本就好了,但之前在我电脑上跑别的代码,一样的保存方式并没有问题。谢谢啦,兄弟
    
    0 0
数据库
使用钉钉扫一扫加入圈子
+ 订阅

分享数据库前沿,解构实战干货,推动数据库技术变革

推荐文章
相似问题