Search code examples
node.jsmongoosemongoose-schema

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


Solution

  • 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.