Mongoosejs 刷新文档 [英] Mongoosejs refresh a document
问题描述
假设我有一个文档,例如: var doc = Model.findOne({name:"name"});
Suppose I have a document for example: var doc = Model.findOne({name:"name"});
现在,如果文档通过数据库的另一个连接进行编辑,文档将无法保存正确的信息.我确实需要它,所以我必须从数据库刷新"或重新下载"它.有没有办法只用对象doc"来做到这一点?
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"?
推荐答案
假设 doc
包含要刷新的文档实例,您可以这样做来一般刷新它:
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;
}
}
);
但是,最好不要持久/缓存超出您对它们的直接需求的 Mongoose 文档实例.缓存您需要快速访问的文档的不可变 _id
,而不是文档本身.
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.
这篇关于Mongoosejs 刷新文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!