2017-06-14 92 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 } } 
    ); 
}