Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using $inc to increment a document property with Mongoose

Tags:

I would like to increment the views count by 1 each time my document is accessed. So far, my code is:

Document     .find({})     .sort('date', -1)     .limit(limit)     .exec(); 

Where does $inc fit in here?

like image 532
Randomblue Avatar asked Dec 24 '11 00:12

Randomblue


People also ask

How do I increment a field in MongoDB?

In MongoDB, the $inc operator is used to increment the value of a field by a specified amount. The $inc operator adds as a new field when the specified field does not exist, and sets the field to the specified amount. The $inc accepts positive and negative value as an incremental amount.

What is $in in Mongoose?

The value of the $in operator is an array that contains few values. The document will be matched where the value of the breed field matches any one of the values inside the array.

How do you use findByIdAndUpdate Mongoose?

Mongoose | findByIdAndUpdate() Function The findByIdAndUpdate() function is used to find a matching document, updates it according to the update arg, passing any options, and returns the found document (if any) to the callback. Installation of mongoose module: You can visit the link to Install mongoose module.


2 Answers

Never used mongoose but quickly looking over the docs here it seems like this will work for you:

# create query conditions and update variables var conditions = { },     update = { $inc: { views: 1 }};  # update documents matching condition Model.update(conditions, update).limit(limit).sort('date', -1).exec(); 

Cheers and good luck!

like image 200
Tyler Brock Avatar answered Sep 23 '22 02:09

Tyler Brock


I ran into another problem, which is kind of related to $inc.. So I'll post it here as it might help somebody else. I have the following code:

var Schema = require('models/schema.js');  var exports = module.exports = {};  exports.increase = function(id, key, amount, callback){    Schema.findByIdAndUpdate(id, { $inc: { key: amount }}, function(err, data){       //error handling    } } 

from a different module I would call something like

var saver = require('./saver.js');  saver.increase('555f49f1f9e81ecaf14f4748', 'counter', 1, function(err,data){     //error handling } 

However, this would not increase the desired counter. Apparently it is not allowed to directly pass the key into the update object. This has something to do with the syntax for string literals in object field names. The solution was to define the update object like this:

exports.increase = function(id, key, amount, callback){     var update = {};    update['$inc'] = {};    update['$inc'][key] = amount;     Schema.findByIdAndUpdate(id, update, function(err, data){       //error handling    } } 
like image 21
peerbolte Avatar answered Sep 24 '22 02:09

peerbolte