2017-02-18 25 views
0

所以,我有一個函數應該在if條件爲真的情況下執行。我只是不知道如何在一個方法中實現它。我有以下代碼:如何編寫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} 
     } 
     } 
    ); 
    }; 
    } 
}); 

所以,萬一如果條件爲真,則$pop功能應該被執行。如果不是,它不應該。我寫了這條if語句,但它不起作用:

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

任何幫助,高度讚賞!謝謝。

回答

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} 
      }); 
     } 
    }; 
}); 
+0

儘管此代碼可能會回答問題,但提供有關如何解決問題和/或爲何解決問題的其他上下文會提高答案的長期價值。 –

+0

非常感謝!實施並完美運作。我猜如果.count> 0告訴if,如果有超過0個項目是$ gt比日期,那麼執行$ pop。這就是我需要的。我只是無法搜索出語法,謝謝。 – Jaybruh

1

包括在未來與上述溶液中更新操作查詢作爲

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 } } 
     ); 
    } 
}); 
+0

謝謝!聽起來非常邏輯。但是,當我使用$和版本時,它會彈出'itemIds'數組中不止一個項目(正好是2個項目)(不知道爲什麼)。我用if()和.count()實現了下面的答案,因爲這也可以很好地工作,我只需要添加.count函數。你的實施會有優勢嗎? – Jaybruh

+1

好處是你不需要使用'userManagement.find({'itemIds':{$ gt:date}})。count()'來對服務器進行額外的調用,所有操作都在'update'函數中完成作爲查詢對象的一部分因此非常有效。 – chridam

相關問題