javascript - 使用 if/else mongodb-update 使 JS 函数更短

标签 javascript mongodb mongodb-query

这个函数可以再短一点吗?我不喜欢 if/else 更新,这几乎是相同的。唯一的区别是 'status.edited': false 仅应在 method = reset 时设置。否则不应修改。

function updateVersion(id, method) {
    var timestamp = new Date().getTime();

    if (method == 'reset') {
        Collection.update(
            { _id: id }, 
            { 
                $set:   { 'status.version': timestamp, 'status.edited': false },
                $unset: { 'status.editing': '' }
            }
        );
    }
    else {
        Collection.update(
            { _id: id },
            { 
                $set:   { 'status.version': timestamp },
                $unset: { 'status.editing': '' }
            }
        );      
    }

}

最佳答案

您可以像这样动态构建查询:

function updateVersion(id, method) {
    var timestamp = new Date().getTime();
    var update = { 
        '$set': { 'status.version': timestamp },
        '$unset': { 'status.editing': '' } 
    };

    if (method === 'reset')
        update['$set']['status.edited'] = false;

    Collection.update( { '_id': id }, update );
}

关于javascript - 使用 if/else mongodb-update 使 JS 函数更短,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33959678/

相关文章:

javascript - 链接标记在 Ember Js 中不起作用

javascript - 如何模拟带有参数的 Angular 服务方法

mongodb - 如何从 MongoDB 聚合中的不同集合添加多个 $match 条件

javascript - Mongoose JS : `TypeError: Object #<Object> has no method ' save'`: Cannot save part of a document?

php - elemMatch 查询在 php 中不起作用

javascript - 使用 loadGeoJSON 时未捕获类型错误

javascript - jQuery SlideToggle 不适用于语义上不相邻的元素

regex - 如何使用 bson 在 GoLang 中为正则表达式编写 mongodb 查询?

mongodb - 如何处理更新时对损坏数据的验证?

node.js - 如何在 MongoDB 的数组中提取项目的一个实例?