Chet
Chet

Reputation: 19829

How to filter Meteor database query results?

I'm having so much trouble finding an elegant way of filtering by mongodb query results against an array of objects I dont want.

I get an array of objects:

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

And I have a few articles that have already been selected and should be returned

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

I find it hard to believe that theres no built in function such as:

articles.remove(selected);

But there isn't, and given the amount we're working with MongoDb in Meteor, I figured someone has already found some good helper functions for doing this and other similar functionality

Thanks

Upvotes: 2

Views: 1079

Answers (3)

David Weldon
David Weldon

Reputation: 64312

As you suggested in your comment, I believe $nin is what you want (yes, it's available in meteor). For example:

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

This is also nice if you are running it on the client because you don't have to call fetch prior to rendering.

Upvotes: 1

Stephan Tual
Stephan Tual

Reputation: 2637

Using underscore.js (present by default in Meteor), try

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

Source: http://underscorejs.org/#difference

Upvotes: 0

Chet
Chet

Reputation: 19829

So I found a reasonable solution, but its incomplete:

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
}

The problem I am still running into is that this doesnt work and keep returning []

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
}

Upvotes: 2

Related Questions