mongoose icon indicating copy to clipboard operation
mongoose copied to clipboard

insertMany middleware

Open jayantasamaddar opened this issue 2 years ago • 3 comments

Dear Mongoose Team,

The post and pre insertMany middleware have the arguments order reversed.

Pre takes in (next, docs), Post takes in (docs, next)

Please follow standardized API design or it gets confusing.

jayantasamaddar avatar Mar 15 '22 11:03 jayantasamaddar

const mongoose = require('mongoose');

const testSchema = new mongoose.Schema({
    name: String
});

testSchema.pre('insertMany', (docs, next) => {
    console.log('==========================PRE===========================')
    console.log('first', docs);
    console.log('second', next);
    if(Array.isArray(docs)) {
        next();
    } else {
        docs();
    }
});

testSchema.post('insertMany', (docs, next) => {
    console.log('==========================POST==========================');
    console.log('first', docs);
    console.log('second', next);
    if(Array.isArray(docs)) {
        next();
    } else {
        docs();
    }
});

const Test = mongoose.model('Test', testSchema);

async function run() {
    await mongoose.connect('mongodb://localhost:27017');
    await mongoose.connection.dropDatabase();

    await Test.insertMany([{name: 'Test'}, {name: 'Testerson'}]);
}

run();

IslandRhythms avatar Mar 16 '22 16:03 IslandRhythms

Something to consider changing for Mongoose 7. I agree this is very confusing.

vkarpov15 avatar Mar 18 '22 18:03 vkarpov15

This is especially confusing in TypeScript code. For example, I have the following code:

Schema.pre('insertMany', async function (results: ISchema[]) {
  if (Array.isArray(results)) {
    for (const item of results) {
      const finder = await Model.findOne({ someId: item.someId })
      if (!finder) {
        throw new Error("Schema must exist before AnotherSchema can be created")
      }
    }
  }
})

Becausepre takes in (next, docs), TypeScript warns that Types of parameters 'results' and 'next' are incompatible.. Thus, I am forced to do Schema.pre('insertMany', async function (next, results: ISchema[]) { for everything to work correctly.

I assume correcting the order might be a breaking change, but I agree with @vkarpov15 that it should be considered for version 7.

assetcorp avatar Nov 20 '22 16:11 assetcorp