我正在寻找一种方法来重构我的部分代码,使其更短更简单,但我不太了解 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;
}
});
}
});
最佳答案
您正在寻找 new
选项参数。 new
选项返回新创建的文档(如果创建了新文档)。像这样使用它:
var query = {},
update = { expire: new Date() },
options = { upsert: true, new: true, setDefaultsOnInsert: true };
// Find the document
Model.findOneAndUpdate(query, update, options, function(error, result) {
if (error) return;
// do something with the document
});
由于upsert
如果没有找到一个文档就会创建一个文档,所以你不需要手动创建另一个。
关于javascript - Mongoose - 如果不存在则创建文档,否则,更新 - 在任何一种情况下都返回文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33305623/