我正在使用 Meteor 和 mongoDB,如果字段“removeTime”低于给定值,我需要从数组中取出整个对象。
集合“items”中的文档具有以下结构:
{
"_id" : "Guy1",
"solvedItems" : {
"items" : [
{
"itemPush" : "item1-b41f50bc24397735_ABC>14607a25c0864858",
"actualTime" : 1501281170509.0,
"removeTime" : 3532817170509.0
},
{
"itemPush" : "item2-691aa30080189962_ABC>14607a25c0864858",
"actualTime" : 1501281255771.0,
"removeTime" : 1532817255771.0
}
]
}
}
例如,给定的值为var givenValue = 2532817255771.0
。所以目标是删除 items-array 中的第二个对象,但第一个对象保留在文档中:
{
"_id" : "Guy1",
"solvedItems" : {
"items" : [
{
"itemPush" : "item1-b41f50bc24397735_ABC>14607a25c0864858",
"actualTime" : 1501281170509.0,
"removeTime" : 3532817170509.0
}
]
}
}
我用 $elemMatch 和 $pull 尝试了很多方法,但没有任何效果。这是我现在所拥有的:
Meteor.methods({
'pullItem': function () {
//Set the givenValue
var givenValue= 2532817255771.0;
//In case there is an element, which is lower than givenValue, execute
if(items.findOne({'_id': "Guy1", 'solvedItems.items': {$elemMatch: {'removeTime':{$lt:givenValue}}}})) {
items.update({'_id': "Guy1"}, {
$pull: {
'solvedItems.items': // Absolutely no idea how to do it
}
});
console.log('pulledOut')
} else {
console.log('letItStayInside')}
}});
我不知道如何删除包含最低值的对象。
我认为您的问题可以通过 JS 数组上的基本过滤器功能解决
var result = {};
var givenValue = 2532817255771.0;
var tmp = {
"_id" : "Guy1",
"solvedItems" : {
"items" : [
{
"itemPush" : "item1-b41f50bc24397735_ABC>14607a25c0864858",
"actualTime" : 1501281170509.0,
"removeTime" : 3532817170509.0
},
{
"itemPush" : "item2-691aa30080189962_ABC>14607a25c0864858",
"actualTime" : 1501281255771.0,
"removeTime" : 1532817255771.0
}
]
}
}
result = tmp.items.filter(function (element){return element.removeTime < givenValue});
结果是预期的数组,另外一个属性可以自己重新赋值,我觉得不是问题。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句