Jun
Jun

Reputation: 551

In Mongoose, Duplicate key error collection with save method

In my project, I'd like to make a simple user management program with MongoDB.

So I built a local server using Express of NodeJS and connected it to MongoDB.

After that, a schema called User was declared in Mongoose, and I made and tested a rest api that simply inserts data.

However, as a second attempt, duplicate key error collection occurred when testing with different uid values. (A first attempt was successful)

Can you tell me what's wrong with my design?

// models/user.js
const mongoose = require('mongoose');

const userSchema = new mongoose.Schema({
    uid: {
        type: String,
        required: true,
        unique: true
    },
    password: {
        type: String,
    },
    name: {
        type: String,
    },
    email: {
        type: String,
    },
    phone: {
        type: String,
    },
    birth: {
        type: Date,
    },
    delivery_password: {
        type: String,
    }
},
    {
        timestamps: true
    }
);

// Create Model & Export
module.exports = mongoose.model('User', userSchema);
// routers/users.js (only routing code)
const User = require('../models/user');

router.get('/test', function (req, res) {
  const user = new User({
    uid: 'lhj23',
    password: 'test',
    name: 'test',
    email: '[email protected]',
    phone: '01000000000',
    birth: new Date('2000-01-01'),
    delivery_password: '1234',
  });

  user.save(function (err) {
    if (err) {
      console.error(err);
      res.json({
        result: 0,
        message: err.message
      });
      return;
    }

    res.json({ result: 1 });
  });
})
// error message
MongoError: E11000 duplicate key error collection: db.users index: id_1 dup key: { id: null }
    at Function.create (C:\test\android\node_modules\mongodb\lib\core\error.js:57:12)
    at toError (C:\test\android\node_modules\mongodb\lib\utils.js:130:22)
    at C:\test\android\node_modules\mongodb\lib\operations\common_functions.js:258:39
    at handler (C:\test\android\node_modules\mongodb\lib\core\sdam\topology.js:943:24)
    at C:\test\android\node_modules\mongodb\lib\cmap\connection_pool.js:350:13
    at handleOperationResult (C:\test\android\node_modules\mongodb\lib\core\sdam\server.js:558:5)
    at MessageStream.messageHandler (C:\test\android\node_modules\mongodb\lib\cmap\connection.js:281:5)
    at MessageStream.emit (events.js:376:20)
    at processIncomingData (C:\test\android\node_modules\mongodb\lib\cmap\message_stream.js:144:12)
    at MessageStream._write (C:\test\android\node_modules\mongodb\lib\cmap\message_stream.js:42:5)
    at writeOrBuffer (internal/streams/writable.js:358:12)
    at MessageStream.Writable.write (internal/streams/writable.js:303:10)
    at Socket.ondata (internal/streams/readable.js:745:22)
    at addChunk (internal/streams/readable.js:309:12)
    at readableAddChunk (internal/streams/readable.js:284:9) {
  driver: true,
  index: 0,
  code: 11000,
  keyPattern: { id: 1 },
  keyValue: { id: null }
}

Edit 1 Calling that rest api, I created user instance like this.

const user = new User({
    uid: 'lhj',
    password: 'test',
    name: 'test',
    email: '[email protected]',
    phone: '01000000000',
    birth: new Date('2000-01-01'),
    delivery_password: '1234',
  });

And, this was a second one.

const user = new User({
    uid: 'lhj23',
    password: 'test',
    name: 'test',
    email: '[email protected]',
    phone: '01000000000',
    birth: new Date('2000-01-01'),
    delivery_password: '1234',
  });

Upvotes: 1

Views: 822

Answers (1)

Aditya Joshi
Aditya Joshi

Reputation: 1053

In your userSchema you have defined uid as unique and when you are calling your /test endpoint you are always passing the same uid which is not unique, instead of that use uuid for the uid field.

const { uuid } = require('uuidv4');
router.get('/test', function (req, res) {
  const user = new User({
   uid: uuid(),
   password: 'test',
   name: 'test',
   email: '[email protected]',
   phone: '01000000000',
   birth: new Date('2000-01-01'),
   delivery_password: '1234',
});
.....
//save here
}

Upvotes: 1

Related Questions