Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Bulk insert duplicate key error #42

Open
smoglica opened this issue Mar 12, 2018 · 2 comments
Open

Bulk insert duplicate key error #42

smoglica opened this issue Mar 12, 2018 · 2 comments

Comments

@smoglica
Copy link

I really like this plugin and it's working really good. Unfortunately currently I'm facing on this issue regarding duplicate keys error which it's blocking my app development somehow.

Info

  • MongoDB v3.6.1
  • mongoose 4.13.4

Let's suppose to have this scenario:

Users array that I want to save into MongoDB

const users = [{
  name: 'Tran Guilbert',
  username: 'tran'
}, {
  name: 'Tambra Shorter',
  username: 'tran'
}];

Current users saved in MongoDB

{
  name: 'Apolonia Milin'
  username: 'tran'
}

user.model.js

import mongoose, {Schema} from 'mongoose';
const URLSlugs = require('mongoose-url-slugs');

const UserSchema = new Schema({
  name: {
    type: String
  },
  username: {
    type: String,
    trim: true,
    required: true
  }
});

UserSchema.plugin(URLSlugs('username', {alwaysRecreate: true, update: true}));
export default mongoose.model('User', UserSchema);

user.controller.js

import User from './user.model';

// POST request for the creation of users
export function create(req, res) {
  const users = req.body; // Array of users

  // We can also try to use User.create(users), doesn't change the issue
  return User.insertMany(users)
    .then(respondWithResult(res, 201))
    .catch(handleError(res));
}

I got the following error:

E11000 duplicate key error collection: mydb.users index: username_1 dup key { : "tran"}.

In this case both insertions fails.

If I dont't have any user saved in the db with username "tran", the first insertion goes fine, but the second one throws the same error.

This issue was already mentioned here and seems really similar to mine, why wasn't taken in consideration with a proper solution until now?

@twoheaded
Copy link

I have the same issue when use MyModel.create(docs). Is it possible to solve this problem?

@talha-asad
Copy link
Owner

Please see #37

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants