crivella
crivella

Reputation: 684

Mongoose Schema.pre insertMany middleware

I'm using mongoose with nodeJs and I'm trying to implement a middleware called when using insertMany . In mongoose documentation there are no example at all, but they confirm that insertMany model function triggers the following middleware: insertMany().

I have a basic User schema and I need insertMany hooks to hash password with bcrypt:

UserSchema.pre('insertMany', async function (err, docs, next) {

  try{
    docs.map(async function (doc, index) {
      // async hash password
      doc.password = await User.hashPassword(doc.password);
    });

  } catch (error) {
    console.log(error);
  }

  next();
});

I'm not posting all schema because all the rest works, including password hashing and 'save' hooks. I cannot understand why I am getting this error when I try to insert many users:

next is not a function

Usually I call next() to proceed to next middleware, but in this case it doesn't work. If I remove next(), code won't go on to next middleware and in both cases users are not inserted.

Can someone help me?

Upvotes: 6

Views: 5613

Answers (1)

Pavlo Kostohrys
Pavlo Kostohrys

Reputation: 299

It is because you provide wrong arguments in callback. Hook apply only 'next' argument. You need change your callback function arguments from (err, docs, next) to (next, docs) and it should work for you.

Details you can see here https://mongoosejs.com/docs/middleware.html#pre

https://mongoosejs.com/docs/middleware.html#types-of-middleware

Upvotes: 5

Related Questions