【问题标题】:How to write an if statement to check whether any item in array is greater than a specific value/date?如何编写 if 语句来检查数组中的任何项目是否大于特定值/日期?
【发布时间】:2017-07-07 22:15:11
【问题描述】:

所以,我有一个函数应该在 if 条件为真的情况下执行。我根本不知道如何在方法中实现它。我有以下代码:

Meteor.methods({
 'popItems': function () {
   var date = new Date().getTime();

    if ( "check if this.userId && any item in the array 'itemIds' is $gt date" ) {

     userManagement.update({
      '_id': this.userId
     },  {
         $pop: {'itemIds': -1}
         }
        } 
      );
    };
  }
});

因此,如果 if 条件为真,则应执行 $pop 函数。如果是假的,它不应该。我为 if 子句写了这个,但它不起作用:

if (this.userId && userManagement.find({
            'itemIds': {$gt: date}})) {...$pop function...}

【问题讨论】:

    标签: arrays mongodb meteor mongodb-query


    【解决方案1】:
    Meteor.methods({
        'popItems': function () {
            var date = new Date().getTime();
    
            if (this.userId && userManagement.find({'itemIds':{ $gt: date}}).count() > 0 ) {
    
                userManagement.update({
                    '_id': this.userId
                },  {
                    $pop: {'itemIds': -1}
                });
            }
        };
    });
    

    【讨论】:

    • 虽然此代码可能会回答问题,但提供有关它如何和/或为什么解决问题的额外上下文将提高​​答案的长期价值。
    • 非常感谢!实施并完美运行。我猜 .count > 0 告诉如果,如果有超过 0 个项目是 $gt 而不是日期,则执行 $pop。这正是我所需要的。我只是找不到语法,谢谢。
    【解决方案2】:

    在更新操作中包含查询

    Meteor.methods({
        'popItems': function () {
            var date = new Date();
            userManagement.update(
                {
                    '_id': this.userId,
                    'itemIds': { '$gt': date }
                },  
                { '$pop': { 'itemIds': -1 } }
            );
        }
    });
    

    在提出上述解决方案时,我做了一些假设。第一个是 itemIds 是一个仅由 Date 对象组成的数组,例如

    itemIds: [
        ISODate("2017-01-25T06:20:00.000Z"),
        ISODate("2017-01-26T06:20:00.000Z"),
        ISODate("2017-01-27T06:20:00.000Z"),
        ...
        ISODate("2017-02-25T06:20:00.000Z")
    ]
    

    更新操作中的上述查询也可以用 $and 运算符指定为:

    Meteor.methods({
        'popItems': function () {
            var date = new Date();
            userManagement.update(
                {
                    '$and': [
                        { '_id': this.userId },
                        { 'itemIds': { '$gt': date } }, 
                    ]
                },          
                { '$pop': { 'itemIds': -1 } }
            );
        }
    });
    

    【讨论】:

    • 谢谢!听起来很有逻辑。但是,当我使用 $and 版本时,它会从“itemIds”数组(不知道为什么)中弹出多个项目(正好 2 个项目)。我用 if () 和 .count() 实现了下面的答案,因为这也可以正常工作,我只需要添加 .count - 东西。您的实施会有优势吗?
    • 优点是您不需要使用userManagement.find({'itemIds':{ $gt: date}}).count() 对服务器进行额外调用,所有操作都在update 函数中作为查询对象的一部分完成,因此非常高效。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-24
    • 2011-03-01
    相关资源
    最近更新 更多