Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Meteor find using $in with array of Ids

Tags:

mongodb

meteor

I'm trying to get back collections using $in and an array of Ids

I have the following but it's not working

var blockByLocation = Blocks.find({location: location});
    var producersArray = [];
    blockByLocation.forEach(function (block) {
        producersArray.push(block.producerId);
    });

    console.log(producersArray);

producersList = Producers.find({$and:[{organizationId: user.organizationId}, {_id:{$in: producersArray}}]}).map(function (obj) {
            return {text: obj.name, id: obj._id};
});
like image 300
Almog Avatar asked Jun 04 '15 18:06

Almog


2 Answers

You could rewrite your code this way:

var producerIds = Blocks.find({
    "location": location
}).map(function (block) { return block.producerId; });

var producersList = Producers.find({
    "organizationId": user.organizationId,
    "_id": { "$in": producerIds }
}).map(function (obj) {
    return {
        "text": obj.name,
        "id": obj._id
    };
});
like image 192
chridam Avatar answered Nov 06 '22 18:11

chridam


Here's a cleaner answer based on Chidrams. Working code example.

var colleagueIds = Posts.find({ type:"colleagues" }).map(function (person) { return person.title; });
        //console.log(colleagueIds);

        return Meteor.users.find({
            "_id": { "$in": colleagueIds }
        });

Note that the map function returns the title cursor of my post object. It'll make sense if your a good Wordpress developer. But, you probably want to return the _id of the object.

like image 2
Andy Avatar answered Nov 06 '22 18:11

Andy