Mongoosejs refresh a document

丶灬走出姿态 提交于 2021-02-19 01:21:17

问题


Suppose I have a document for example: var doc = Model.findOne({name:"name"});

Now if the document gets edited trough another connection the the database, doc doesn't hold the right information. I do need it, so I have to "refresh" or "redownload" it from the database. Is there any way to do this with only the object "doc"?


回答1:


Assuming doc contains the document instance to refresh, you can do this to generically refresh it:

doc.model(doc.constructor.modelName).findOne({_id: doc._id},
    function(err, newDoc) {
        if (!err) {
            doc = newDoc;
        }
    }
);

However, it's better to not persist/cache Mongoose document instances beyond your immediate need for them. Cache the immutable _id of docs you need to quickly access, not the docs themselves.




回答2:


Sorry I know this is old but I have a better solution in case anyone else is still looking around.

What you can do in this situation of concurrent access to the same document is perform a normal save.

Mongoose uses the __v property of an object to make sure old instances don't overwrite the newest ones.

So if you have 2 instances of doc.__v = 0, and A saves first, the db now has doc.__v = 1. So that when B saves, it'll error and because B.__v = 0, not 1. So what you can do is then catch the error (it should be a specific mongoose error) and handle it by refreshing the object, (which should bump it up to __v = 1) then either SAVE it or not SAVE it depending on what you want to do.

so in code

doc.save(function (err, _doc) {
    if (err) {
        if (err.some_error_property_telling_you_version_was_wrong) {
            // Do your business here 
            // Refresh your object
            // Model.findById(doc._id, function (err, _refreshed_doc) {});
            // doc = _refreshed_doc;
            // doc.set('property', value); set the value again
            // Then re-save? or maybe make this a recursive function,
            // so it can keep trying to save the object?
        } else {
            // Handle it like a normal error
        }
    }
});  


来源:https://stackoverflow.com/questions/13961303/mongoosejs-refresh-a-document

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