mongoose – 创build文件,如果不存在,否则,更新 – 返回文件在任何情况下

我正在寻找一种方法来重构我的代码的一部分,以缩短和简化,但我不知道mongoose很好,我不知道如何继续。

我试图检查一个文档的存在集合,如果它不存在,创build它。 如果确实存在,我需要更新它。 无论哪种情况,我都需要访问文档的内容。

我迄今为止设法做的是查询特定文档的集合,如果找不到,则创build一个新文档。 如果发现,我更新它(目前使用date作为这个虚拟数据)。 从那里我可以访问从我最初的find操作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和其他相关的方法,但我不知道它们是否适合我的用例,或者如果我明白如何正确使用它们。 任何人都可以指向正确的方向吗?

(可能)相关问题:

  • 如何检查更新过程中数据库中是否已经存在数据(Mongoose And Express)
  • Mongoose.js:如何实现创build或更新?
  • NodeJS + Mongo:插入如果不存在,否则 – 更新
  • 用Mongoose返回更新的集合

编辑

在我的search中,我没有遇到过指向我的问题,但是在回顾了那里的答案之后,我想出了这个问题。 在我看来,它确实更漂亮,而且是有效的,所以除非我做了一些可怕的错误,否则我认为我的问题可能会被封闭。

我会很感激我的解决scheme的任何额外的input。

 // 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选项返回新创build的文档(如果创build了新文档)。 像这样使用它:

 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创build一个文档,如果没有find一个文档,你不需要手动创build另一个。