【发布时间】:2016-01-23 04:24:45
【问题描述】:
我正在寻找一种方法来重构我的部分代码,使其更短更简单,但我不太了解 Mongoose,我不知道如何继续。
我正在尝试检查集合中是否存在文档,如果不存在,则创建它。如果它确实存在,我需要更新它。无论哪种情况,我都需要在之后访问文档的内容。
到目前为止,我已经设法在集合中查询特定文档,如果未找到,则创建一个新文档。如果找到,我会更新它(目前使用日期作为虚拟数据)。从那里我可以访问从我最初的find 操作中找到的文档或新保存的文档,这很有效,但必须有更好的方法来完成我所追求的。
这是我的工作代码,没有分散注意力的额外内容。
var query = Model.find({
/* query */
}).lean().limit(1);
// Find the document
query.exec(function(error, result) {
if (error) { throw error; }
// If the document doesn't exist
if (!result.length) {
// Create a new one
var model = new Model(); //use the defaults in the schema
model.save(function(error) {
if (error) { throw error; }
// do something with the document here
});
}
// If the document does exist
else {
// Update it
var query = { /* query */ },
update = {},
options = {};
Model.update(query, update, options, function(error) {
if (error) { throw error; }
// do the same something with the document here
// in this case, using result[0] from the topmost query
});
}
});
我研究了findOneAndUpdate 和其他相关方法,但我不确定它们是否适合我的用例,或者我是否了解如何正确使用它们。谁能指出我正确的方向?
(可能)相关问题:
- How to check if that data already exist in the database during update (Mongoose And Express)
- Mongoose.js: how to implement create or update?
- NodeJS + Mongo: Insert if not exists, otherwise - update
- Return updated collection with Mongoose
编辑
我在搜索时没有遇到向我指出的问题,但在查看了那里的答案后,我想出了这个。在我看来,它当然更漂亮,而且它有效,所以除非我做错了什么可怕的事情,否则我认为我的问题可能会结束。
如果我的解决方案有任何额外的意见,我将不胜感激。
// Setup stuff
var query = { /* query */ },
update = { expire: new Date() },
options = { upsert: true };
// Find the document
Model.findOneAndUpdate(query, update, options, function(error, result) {
if (!error) {
// If the document doesn't exist
if (!result) {
// Create it
result = new Model();
}
// Save the document
result.save(function(error) {
if (!error) {
// Do something with the document
} else {
throw error;
}
});
}
});
【问题讨论】:
-
阙:Mongoose.js:如何实现创建或更新?答:stackoverflow.com/questions/7267102/…
-
老实说,我现在觉得自己很愚蠢。我在搜索时没有找到那个问题,但回想起来,答案似乎很容易掌握。感谢您的帮助!
标签: javascript node.js mongoose refactoring