Mongoose pre findOneAndUpdate hook issues

后端 未结 4 741
春和景丽
春和景丽 2021-01-01 19:36

I\'m trying to update counts on a pre hook. The issue is that for some unknown reason the findOneAndUpdate hook doesn\'t have access to the document, as far as

4条回答
  •  梦谈多话
    2021-01-01 19:45

    Another solution is to use the official MongoDB documentation on middleware. They explain why "this" does not refer to the document itself. You may try something in that sense:

       source.pre('findOneAndUpdate', async function(next) {
         const docToUpdate = await this.model.findOne(this.getFilter());
            //modify the appropriate objects
         docToUpdate.save(function(err) {
           if(!err) {
             console.log("Document Updated");
            }
         });
        console.log(docToUpdate); 
         // The document that `findOneAndUpdate()` will modify
           next();   
         });
    

提交回复
热议问题