syllogistic
syllogistic

Reputation: 187

MongoClient Native FindAndModify "Need update or remove" Error

My node.js client looks like this:

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

MongoClient.connect(mongoendpoint, function(err, db) {
        if(err) throw err;
        var collection = db.collection('test-collection');

        var ws = new WebSocket(websocket_Endpoint);
        ws.on('open', function() {
                log.info('Connected.');
        });

        ws.on('message', function(data, flags) {

                wsevent = JSON.parse(data);

                var args = {
                        'query': {
                                id: '1.2.3.4'
                        },
                        'update': {
                                $set: {
                                        lastseen: "201405231344"
                                },
                                $addToSet: {
                                        record: "event123"
                                }
                        },
                        'new': true,
                        'upsert': true
                };

                collection.findAndModify(args, function(err, doc){
                        log.info(err);
                });
        });
});

When I run this, I get the following error:

info:  name=MongoError, ok=0, errmsg=need remove or update

I can't figure out why. I can run the exact same args json above using RoboMongo and the query works just fine.

Robomongo Query

db['test-collection'].findAndModify({"query":{"id":"1.2.3.4"},"update":{"$setOnInsert":{"lastseen":"201405231344"},"$addToSet":{"record":"event123"}},"new":true,"upsert":true});

What am I missing?

Upvotes: 3

Views: 1431

Answers (1)

Neil Lunn
Neil Lunn

Reputation: 151122

Your args section is wrong, it should be an array and does not need key values for "query" and "update". And the "options" value also needs to be an object (sub-document):

           var args = [
                    { id: '1.2.3.4' },
                    {
                            $set: {
                                    lastseen: "201405231344"
                            },
                            $addToSet: {
                                    record: "event123"
                            }
                    },
                    {
                        'new': true,
                        'upsert': true
                    }
            ];

Or specifically in the call:

collection.findAndModify(
    { id: '1.2.3.4' },
    { 
        $set: { lastseen: "201405231344" },
        $addToSet: { record: "event123" }
    }, 
    {
        'new': true,
        'upsert': false
    },
    function(err, doc){

Examples are also included on the manual page.

Upvotes: 2

Related Questions