robinnnnn
robinnnnn

Reputation: 1735

MongoDB - .update() vs .findAndModify() error

The following is more of a question out of curiosity.

I'm currently running a script that updates each user in my database by pushing an ObjectID reference to into an array within the user schema.

From my understanding, there is little difference between the .update and .findAndModify commands in MongoDB. However, I receive an error when I use .findAndModify whereas .update works perfectly well.

Here's my script:

var panos = db.panos.find();
var total = 0;
while(panos.hasNext()) {
    var pano = panos.next();
    var author = db.users.findOne({ _id: pano._id});

    /* here I use the .update command */
    db.users.update(
        { _id: ObjectId(pano.author) },
        { $addToSet: { panos: pano._id }}
    );

    total++;
    print('total looked at:', total)
}

And the users are updated as expected. When I replace .users() with .findAndModify(), the following error logs in the console:

Error: findAndModifyFailed failed: {
    "ok" : 0,
    "errmsg" : "no such command: _id",
    "code" : 59,
    "bad cmd" : {
        "_id" : ObjectId("5616dd0a35ea7932106b7c57"),
        "findandmodify" : "users"
    }
}

It looks like the _id query is giving a problem, but I can't wrap my head around why. I've tried replacing ObjectId(pano.author) with just pano.author but to no avail.

TL;DR: .update works where .findAndModify doesn't

Upvotes: 2

Views: 1075

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 312065

In the shell, findAndModify takes a single parameter object rather than separate parameters like update, so you need to call it as:

db.users.findAndModify({
    query: { _id: ObjectId(pano.author) },
    update: { $addToSet: { panos: pano._id }}
});

Upvotes: 3

Related Questions