vkarpov15 / mongoose-unique-array

Plugin to handle `save()` with `unique` in arrays
Apache License 2.0
12 stars 6 forks source link

Duplicate items when use autopopulate plugin #9

Closed apascualm closed 4 years ago

apascualm commented 4 years ago

Hello all,

I have a problem when I use the autopopulation plug-in and I want to insert an objectId into the array instead of the referenced model.

When insert the objectId this is inserted but in the next check this throw a error and the collection will be locked.

I use mongoose 5.8.x and node 12.x.

The following code is an example that when i get the error.

const schema = new Schema(
  {
    userId: {
      type: Schema.Types.ObjectId,
      require: true,
      unique: true,
    },
    roles: [
      {
        type: Schema.Types.ObjectId,
        ref: 'roles',
        autopopulate: true,
        unique: true,
      },
    ],
  },
  { timestamps: true },
);
schema.plugin(arrayUniquePlugin);
schema.plugin(autoPopulate);

const model = mongoose.model('usersWithPermissions', schema);
const user = model.findbyId(userId)
user.roles.push(roleId);
user.save();

I will try to send a pull request with my solution.

Thanks