如何过滤Meteor数据库查询结果?

时间:2013-08-28 00:00:28

标签: javascript json mongodb meteor

我很难找到一种优雅的方法,通过mongodb查询结果对我不想要的对象数组进行过滤。

我得到一个对象数组:

var articles = Tips.find().fetch();

我有一些已经被选中的文章应该被退回

var selected = [{Object}, {Object}];

我发现很难相信没有内置功能,例如:

articles.remove(selected);

但是没有,并且考虑到我们在Meteor中使用MongoDb的数量,我认为有人已经找到了一些好的辅助函数来执行此操作和其他类似的功能

由于

3 个答案:

答案 0 :(得分:2)

所以我找到了一个合理的解决方案,但其不完整:

Array.prototype.removeObjWithValue = function(name, value){
    var array = $.map(this, function(v,i){
        return v[name] === value ? null : v;
    });
    this.length = 0; //clear original array
    this.push.apply(this, array); //push all elements except the one we want to delete
}

Array.prototype.removeObj = function(obj){
    var array = $.map(this, function(v,i){
        return v["_id"] === obj["_id"] ? null : v;
    });
    this.length = 0; //clear original array
    this.push.apply(this, array); //push all elements except the one we want to delete
}

我仍然遇到的问题是这不起作用并继续返回[]

Array.prototype.removeObjs = function(objs){
    var array = this;
    console.log(array);
    $.each(objs, function (i,v) {
        array.removeObj(v);
        console.log(array);
    })
    console.log(array);
    this.length = 0; //clear original array
    this.push.apply(this, array); //push all elements except the ones we want to delete
}

答案 1 :(得分:1)

正如您在评论中所建议的,我相信$nin就是您想要的(是的,它可以在流星中找到)。例如:

var selectedIds = _.pluck(selected, _id);
var articles = Tips.find({_id: {$nin: selectedIds}});

如果您在客户端上运行它,这也很好,因为您不必在呈现之前调用fetch

答案 2 :(得分:0)

使用underscore.js(默认情况下在Meteor中出现),尝试

_.difference(articles, [{Object}, {Object}]);

来源:http://underscorejs.org/#difference