2017-06-14 62 views
1

此Meteor服務器代碼假設將一個對象附加到數組,並使用新數組或不存在的空數組更新集合。將數組更改爲整數

後面的代碼removeFromPendingArr被調用。
但是,mongo shell顯示數組的值爲1,而不是數組[]或空或填充。
任何想法爲什麼以及如何解決它? thx

'addToPendingArr': function (myObj) { 
     let results = []; 
     let pendingArr = Meteor.users.findOne({_id: ab.userIdForAB()}).myArr; 

     if (typeof pendingArr === 'object') { 
     results = pendingArr.push(myObj); 
     Meteor.users.update({_id: ab.userIdForAB()}, {$set: {myArr: results}}); 
     } 
     return results; 
    }, 


'removeFromPendingArr': function (xxx) { 
    let results = []; 
    let pendingArr = Meteor.users.findOne({_id: ab.userIdForAB()}).myArr; 

     if (typeof pendingArr === 'object' && pendingArr.length > 0) { 
     results = pendingArr.filter(y => y.mark !== xxx); 
     } 

     Meteor.users.update({_id: ab.userIdForAB()}, {$set: {myArr: results}}); 
     return results; 
    }, 
+0

'results = pendingArr.push(myObj);' - 結果'results'是數組的新長度-see [「Documentation」](https://developer.mozilla.org/en/ docs/Web/JavaScript/Reference/Global_Objects/Array/push?v = control#Return_value) –

+0

我明白了。你想發佈修復? thx –

+0

所以,你不知道?使用'pendingArr'的地方你已經使用了'results'(稍後在代碼中) - 哦,不那麼容易,因爲結果應該是一個數組......你怎麼知道它,一旦你知道結果不是火箭手術你認爲它是什麼,使用你需要的使用 –

回答

1

爲什麼不使用Mongo的$ push和$ pull?

'addToPendingArr': function (myObj) { 
    Meteor.users.update(
     { _id: ab.userIdForAB() }, 
     { $push: { myArr: myObj } } 
    ); 
} 

'removeFromPendingArr': function (xxx) { 
    Meteor.users.update(
     { _id: ab.userIdForAB() }, 
     { $pull: { myArr: xxx } } 
    ); 
}