user3848987
user3848987

Reputation: 1657

Get ID of affected document by using update()

I'm using this for doing an upsert:

Articles.update(
    { title: title },
    { 
        title: title,
        parent: type
    },
    { upsert: true }, 
    function(res) {
        return console.log(res);
    }
);

console.log(needToGetID);

Now I need to get the _id of the document which has been updated or inserted. I thought I can get that via callback, but res is undefined. I assume there is just one unique document which is defined by the query.

Update

Forgot to mention that I'm using meteor...

Upvotes: 11

Views: 12015

Answers (1)

Blakes Seven
Blakes Seven

Reputation: 50406

The intent of .update() is to basically just "update" the matching document(s) ( as "multi" can also be applied here ) and be done with it, therefore that especially considering this "could" be applied to multiple documents then returning such information would not really make sense in the terms of that operation.

However if your intent is to modifiy a single "specific docucment", then the .findOneAndUpdate() method would apply assuming you are using mongoose:

Articles.findOneAndUpdate(
    { title: title },
    {
        title: title,
        parent: type
    },
    { upsert: true, new: true  }, 
    function(res) {
        return console.log(res);
    }
);

Also note the new: true which is important, as without it the default behavior is to return the document "before" it was modified by the statement.

At any rate, as the return here is the document that is matched and modified, then the _id and any other value is present in the response.


With meteor you can add a plugin to enable .findAndModify() which is the root method:

meteor add fongandrew:find-and-modify

And then in code:

Articles.findAndModify(
    {
        "query": { title: title },
        "update": {
            title: title,
            parent: type
        },
        "upsert": true, 
        "new": true  
    }, 
    function(res) {
        return console.log(res);
    }
);

Note that you should also really be using the $set operator, as without it the changes basically "overwrite" the target document:

Articles.findAndModify(
    {
        "query": { "title": title },
        "update": {
            "$set": {
                "parent": type
            }
        },
        "upsert": true, 
        "new": true  
    }, 
    function(res) {
        return console.log(res);
    }
);

Upvotes: 10

Related Questions