Get ID of affected document by using update()

女生的网名这么多〃 提交于 2021-02-18 20:59:53

问题


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...


回答1:


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);
    }
);


来源:https://stackoverflow.com/questions/32679561/get-id-of-affected-document-by-using-update

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!