Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 351
syllogistic Avatar asked Feb 18 '26 03:02

syllogistic


1 Answers

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.

like image 199
Neil Lunn Avatar answered Feb 20 '26 18:02

Neil Lunn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!