Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mongoose calling .find inside a pre('save') hook

Currently I'm trying to do the following:

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

ItemSchema.pre('save', async function() {
  try{
     let count = await ItemSchema.find({name : item.name}).count().exec();
     ....
     return Promise.resolve();
  }catch(err){
     return Promise.reject(err)
  }
});

module.exports = mongoose.model('Item', ItemSchema);

But I Just get the following Error:

TypeError: ItemSchema.find is not a function

How do I call the .find() method inside my post('save') middleware ? (I know, that there is a unique property on Schmemas. I have to do it this way to suffix the name string if it already exists)

mongoose version : 5.1.3 nodejs version : 8.1.1 system : ubuntu 16.04

like image 373
sami_analyst Avatar asked Oct 29 '25 19:10

sami_analyst


1 Answers

find static method is available on models, while ItemSchema is schema.

It should be either:

ItemSchema.pre('save', async function() {
  try{
     let count = await Item.find({name : item.name}).count().exec();
     ....
  }catch(err){
     throw err;
  }
});

const Item = mongoose.model('Item', ItemSchema);
module.exports = Item;

Or:

ItemSchema.pre('save', async function() {
  try{
     const Item = this.constructor;
     let count = await Item.find({name : item.name}).count().exec();
     ....
  }catch(err){
         throw err;
  }
});

module.exports = mongoose.model('Item', ItemSchema);

Notice that Promise.resolve() is redundant in async function, it already returns resolved promise in case of success, so is Promise.reject.

like image 60
Estus Flask Avatar answered Nov 01 '25 09:11

Estus Flask



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!