talha-asad / mongoose-url-slugs

Create URL compatiable slugs on mongoose models, ensuring uniqueness.
MIT License
40 stars 22 forks source link

Bulk insert duplicate key error #42

Open smoglica opened 6 years ago

smoglica commented 6 years ago

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

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 commented 6 years ago

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

talha-asad commented 6 years ago

Please see #37