Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update document on pre or post query hook in mongoose?

I am trying to update a field on a query hook. For example:

var mySchema = new Schema({
  name: String,
  queryCount: {type: Number, default:0}
});

I want to increment and update queryCount field on each find or findOne query.

mySchema.post('find', function (doc) {
  // here is the magic
});

I have tried a few things but no success so far. Can I achieve this in model or do I have to do it in the controller?

like image 608
s.alem Avatar asked Jul 15 '15 00:07

s.alem


People also ask

What is pre hook in Mongoose?

On my journey to explore MongoDB and Mongoose's powerful features over the years, I encountered something called pre and post hooks, few years back. They are simple yet powerful tools with which you can manipulate model instances, queries, perform validation before or after an intended database operation etc.

What is the use in pre In Mongoose?

According to the official mongoose documentation here – Middleware (also called pre and post hooks) are functions which are passed control during execution of asynchronous functions. Middleware is specified on the schema level and is useful for writing plugins.

What is findById in Mongoose?

In MongoDB, all documents are unique because of the _id field or path that MongoDB uses to automatically create a new document. For this reason, finding a document is easy with Mongoose. To find a document using its _id field, we use the findById() function.

Does update call save in Mongoose?

Working with save() When you create an instance of a Mongoose model using new , calling save() makes Mongoose insert a new document. If you load an existing document from the database and modify it, save() updates the existing document instead.


2 Answers

What you want is a post init hook

mySchema.post('init', function (doc) {
  doc.queryCount++;
  doc.save();
});
like image 57
laggingreflex Avatar answered Oct 10 '22 08:10

laggingreflex


Alternatively, you could use a mongoose static method which internally calls findAndUpdate()

mySchema.statics.findWithIncrement = function (query, callback) {

    this.findAndUpdate(query, { $inc: { queryCount: 1 })
        .exec(function(err, res) {

            if (err) return callback(err);

            //Handle response
        });
}

And then use the method in your controllers:

MyModel.findWithIncrement({name: "someName"}, function (err, result) {

})
like image 2
ZeMoon Avatar answered Oct 10 '22 09:10

ZeMoon