MadPhysicist
MadPhysicist

Reputation: 5831

UpdateMany Not a Function MongoDB + Node

I am writing a piece of code to be run on an npm-cron timer. Here it is:

var CronJob = require('cron').CronJob;
var job = new CronJob({
  cronTime: '* * * * *',
  onTick: function() {
    var monk = require('monk'); // persistence module over MongoDB
    var db = monk('localhost:27017/test');

    console.log("Hello from the Cron job! " + new Date());
    var collection = db.get('Activity');

    collection.updateMany({"repetitions.today": {$gt: 0}},
    {
        $set: {
            "repetitions.today": 0,
        }
    }, function(err, activity){
        if (err) throw err;
    });


  },
  start: true,
  timeZone: 'America/Los_Angeles'
});
job.start();

The problem is that I get an error on the collection.updateMany() line. The error states that

updateMany is not a function

On the other hand, if i use update() instead of updateMany(), the code works (but only on the first item in Mongo collection, as expected). What am I doing wrong and what could be causing this?

I tried re-writing this using foreach() but it is also not recognized as a function.

Upvotes: 1

Views: 2236

Answers (1)

programmerj
programmerj

Reputation: 1684

Hmm....

Might want to try something like this (ES6)

db.collection('Activity').updateMany({"repetitions.today": {$gt: 0}},
{
    $set: { "repetitions.today": 0 }
}).then(r => {
    console.log('Success!');
}).catch(err => {
    console.log('Error - ' + err);
});

Upvotes: 2

Related Questions