user3094755 user3094755 - 6 months ago 76
Javascript Question

MongoDB findAndModify

I have a collection and want to update or create new document and $inc counter.

I have tried to move the update / upsert objects around, but to no effect.

Mongo Version is 3.0.11.

update = {
query: {
_id: "ABCDEFG1234"
update: {
$setOnInsert: {
$inc: {
counter: 1
new: true,
upsert: true

DB.collection('stats').findAndModify(update,function(e,d) { if (e) { console.log(e);} })

{ MongoError: need remove or update
at Function.MongoError.create (~/mongodb/node_modules/mongodb-core/lib/error.js:31:11)
at commandCallback (~/mongodb/node_modules/mongodb-core/lib/topologies/server.js:1154:66)
at Callbacks.emit (~/mongodb/node_modules/mongodb-core/lib/topologies/server.js:119:3)
at .messageHandler (~/mongodb/node_modules/mongodb-core/lib/topologies/server.js:295:23)
at Socket.<anonymous> (~/mongodb/node_modules/mongodb-core/lib/connection/connection.js:285:22)
at emitOne (events.js:96:13)
at Socket.emit (events.js:188:7)
at readableAddChunk (_stream_readable.js:172:18)
at Socket.Readable.push (_stream_readable.js:130:10)
at TCP.onread (net.js:542:20)
name: 'MongoError',
message: 'need remove or update',
ok: 0,
errmsg: 'need remove or update' }


I tried

var find = { member_id: "ABCDEFG1234" };
var update = { $set: { update: }, $inc: { web_visit: 1 } };
var options = { new: true, upsert: true, };
DB.collection('stats').findAndModify(find,update,options,fun‌​ction(e,d) {
if (e) { console.log(e);}

But it now silently fails with nothing in the 'stats' collection.


Your update query is wrongly composed; you are nesting operators which just throws an error. Since the operation you want is to set a counter field and increment it within the update, a single $inc operator would just suffice because if the counter field does not exist, $inc creates the field and sets the field to the specified value.

So a correct update operation using the Node.js driver's findAndModify() method signature would look like:

    { "_id": "ABCDEFG1234" }, // query object to locate the object to modify
    [["_id", "asc"]], // sort array
    { "$inc": { "counter": 1 } }, //document (object) with the fields/vals to be updated
    { "new": true, "upsert": true }, // options to perform an upsert operation.
    function(error, doc) { if (doc) { console.log(doc); } }