简体   繁体   中英

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?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM