Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoosejs refresh a document

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"?

like image 456
urban Avatar asked Dec 19 '12 21:12

urban


1 Answers

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.

like image 195
JohnnyHK Avatar answered Oct 25 '22 14:10

JohnnyHK