mongoose-sequence icon indicating copy to clipboard operation
mongoose-sequence copied to clipboard

Auto increment id don't work with Model.insertMany

Open phong-et opened this issue 4 years ago • 3 comments

Hi guys, as title, has anyone got this issue like me ?

I have a productSchema and plugged autoIncrement

const productSchema = new Schema({
    _id: Number,
    // ...
})
productSchema.plugin(autoIncrement, {inc_field:'_id'})
const Product = db.model('product', productSchema, 'product_new');

Use .save it works well, _Id field value is a Number

jsonProduct = {...}
let product = new Product(jsonProduct)
    product.save(function (err, product) {
      if (err) return console.error(err);
      db.connection.close()
});

Use .insertMany, _id field is ObjectID not a Number

jsonProducts = [{...},{...}...]
Product.insertMany(jsonProducts, function (err, product) {
      if (err) return console.error(err);
      db.connection.close()
});

phong-et avatar Oct 11 '19 13:10 phong-et

I have the same problem as in #7, but the id field wasn't created at all. The code is in #83. Model Foo uses .save() and the fooId field gets created. Model Bar uses .insertMany() and the barId field doesn't get created at all. (I tried new Bar(...).save() and that did create the barIds correctly.)

@ramiel, is it possible that #7 has reappeared? Or was it not possible to fix that issue and the workaround is to use the slow .create()?

dandv avatar Apr 15 '20 02:04 dandv

Any fix on this?

sajadghawami avatar Jul 01 '20 15:07 sajadghawami

So, as specified on #7 this cannot be solved. insertMany doesn't call the necessary middlewres and so using several create is the way to go

ramiel avatar Jul 02 '20 15:07 ramiel