mongoose
mongoose copied to clipboard
insertMany middleware
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.
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();
Something to consider changing for Mongoose 7. I agree this is very confusing.
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.