node.js - Mongodb find and then update -
i want run query gets documents has 'active' field true , run custom function on them checks if 'date' field inside document older 10 days. if both of them true make active field false.
this how current code looks like:
db.ad.find( { $and : [ // check if active true , $where clause equals true { 'active' : true }, { '$where' : function() { // custom compare function var date = new moment(this.date); // gets date current document var date2 = new moment(); return math.abs(date.diff(date2, 'days')) > 10; } } ]}, function(err, result) { // how update document here? } );
can tell me how update documents after find query?
use update()
method $set
modifier operator update active field. update query object, can set date object ten days previous subtracting ten date:
var d = new date(); d.setdate(d.getdate() - 10); var query = { /* query object find records need updated */ "active": true, "date": { "$lte": d } }, update = { /* replacement object */ "$set": { "active": false } }, options = { /* update records match query object, default false (only first 1 found updated) */ "multi": true }; db.ad.update(query, update, options, callback);
-- edit --
using momentjs library, getting date 10 days ago can simple (with add()
method)
d = moment().add(-10, 'days');
or using subtract()
method
d = moment().subtract(10, 'days');
Comments
Post a Comment