javascript - Mongoose - 如果不存在则创建文档,否则,更新 - 在任何一种情况下都返回文档

标签 javascript node.js mongoose refactoring

我正在寻找一种方法来重构我的部分代码,使其更短更简单,但我不太了解 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 和其他相关方法,但我不确定它们是否适合我的用例,或者我是否了解如何正确使用它们。谁能指出我正确的方向?

(可能)相关问题:


编辑

我在搜索时没有遇到向我指出的问题,但在查看了那里的答案后,我想出了这个。在我看来,它肯定更漂亮,而且它有效,所以除非我做错了什么可怕的事情,否则我认为我的问题可能会结束。

如果我的解决方案有任何额外的意见,我将不胜感激。

// 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/

相关文章:

javascript - jQuery 触发 addEventListener 注册的 mousedown

node.js - COR 错误 : Google Oauth from React to Express (PassportJs validation)

javascript - Mongodb $graphLookup 构建层次结构

javascript - Mongoose 和 GraphQL 查询

node.js - 无效的架构配置 : `model` is not a valid type within the array `characters`

javascript - Javascript的string.split的精确定义是什么?

javascript - http toPromise 返回一个对象

javascript - 带有子级 div 的省略号

linux - 我可以在非 ssh 应用程序中使用 ssh key 进行身份验证吗?

node.js - 'yarn' 不是内部或外部命令,也不是可运行的程序或批处理文件