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?
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.
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.
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.
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!
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 } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With