Mongoose find array with $in

41,629

If teamIds is already an array, then you shouldn't wrap it in another array:

Team.find({
    '_id': { $in: teamIds }
}, function(err, teamData) {
    console.log("teams name  " + teamData);
});

Or, if teamIds is a string of comma-separated id values, you need to convert it into an array of values using split:

Team.find({
    '_id': { $in: teamIds.split(',') }
}, function(err, teamData) {
    console.log("teams name  " + teamData);
});
Share:
41,629
Admin
Author by

Admin

Updated on July 11, 2020

Comments

  • Admin
    Admin almost 4 years
    Team.find({
            '_id': { $in: [
                teamIds
            ] }
        }, function(err, teamData) {
            console.log("teams name  " + teamData);
        });
    

    This code gives us undefined back.. But in the var teamIds is this:

    545646d5f5c1cce828982eb7,
    545646d5f5c1cce828982eb8,
    54564af5c9ddf61e2b56ad1e,
    54564c1f1de201782bcdb623,
    54564d2fc660a7e12be6c7a2,
    54564df985495f142c638f9f,
    54564eadb511f1792c9be138,
    54564ec40cf6708a2cd01c81,
    54564ee495f4aea22cf23728
    

    Does anybody see the error?

  • Pete
    Pete almost 4 years
    Would _id not in quotes work? Team.find({ _id: { &in: teamIds } })
  • tlt
    tlt over 2 years
    @Pete yes "_" and "$" are legal variable chars.