natedog
natedog

Reputation: 141

mongoDB node.js findAndModify troubles

I am doing an online course about MongoDB which is unfortunately a little out of date. It seems some of the functions have changed (course is using version 1.4 while I am using 3.0.)

Here is the code I am having trouble with, which I have tried to bring up to date with the current version of MongoDB:

app.js

var MongoClient = require('mongodb').MongoClient;

MongoClient.connect('mongodb://localhost:27017/course', function(err, db) {
if (err) throw err;

db.collection['counters'].findAndModify({
    query: {
        name: 'comments'
    },
    update: {
        $inc: {
            counter: 1
        }
    },
    new: true
}, function(err, doc) {
    if (err) throw err;

    if (!doc) {
        console.dir('No counter found for comments.');
    } else {
        console.dir('Number of comments: ' + doc.counter);
    }

    return db.close();
});
});

If I run the same findAndModify through the Mongo shell I get the anticipated result (increment the counter and display the new document,) but when I run this with node it has no effect on the database and throws this error:

TypeError: Cannot call method 'findAndModify' of undefined

Any tips?

Upvotes: 0

Views: 1925

Answers (4)

natedog
natedog

Reputation: 141

Whoops, I just had the wrong kind of brackets. Should have had:

db.collection('counters')

instead of

db.collection['counters']

Almost like T_G said.

Upvotes: 1

HP Frei
HP Frei

Reputation: 126

use this now:

db.collection('counters').findOneAndUpdate(
    {name: 'comments'},     //query
    {$inc: {counter: 1}},   //update
    {                                               //options
        upsert: true,            // create the doc when it's not there
        returnOriginal:false     // return the modified doc *(new is not supported here!)
    }, 
    function(err, r){       //callback
        if(err) throw err;
        console.log('counter: '+r.value.counter);
    }
);

Upvotes: 1

taylorc93
taylorc93

Reputation: 3716

From the mongodb docs:

Existing collections can be opened with collection

db.collection([[name[, options]], callback);

If strict mode is off, then a new collection is created if not already present.

So you need to do this:

db.collection('counters', function(err, collection){
    collection.findAndModify({
        query: {
            name: 'comments'
        },
        update: {
            $inc: {
                counter: 1
            }
        },
        new: true
    }, function(err, doc) {
        if (err) throw err;

        if (!doc) {
            console.dir('No counter found for comments.');
        } else {
            console.dir('Number of comments: ' + doc.counter);
        }
    });
});

Upvotes: 0

user2941651
user2941651

Reputation:

Please try:

db.counters('counters').findAndModify

instead of:

db.collection['counters'].findAndModify

Upvotes: 1

Related Questions