Prithviraj Mitra
Prithviraj Mitra

Reputation: 11842

Query model with array in mongodb

I am new in node and MongoDB.

I am trying to query a model with an array.

The array looks like this

 var grArr =  [ '5aabc39a3d88101e4b52c861', '5ac3a1fe83d45353bc6a995c' ]

And the query is

Group.find().where({ _id: { $in: grArr }}).exec(function(err,gdoc){
      if(err)
      {
         callback({err:err,message:"Error looking up company"});
      }
      else
      {
         console.log(gdoc.companies); //Gives undefined
         callback(null,gdoc.companies);
      }
});

The query returns undefined.

Any help is highly appreciated.

Upvotes: 0

Views: 69

Answers (3)

Deval
Deval

Reputation: 255

Try this,

Group.find({ _id: { $in:arr }).lean().exec().then((result) => {

}, (err) => {

});

Upvotes: 0

Paradise228
Paradise228

Reputation: 717

There is 2 ways to perform a query with mongoose, and it seems to me that you're mixing both of them.

  • Find should be called with your query as parameter:

And you get something like

Group.find({ _id: { $in: grArr }}, function(err,gdoc){
      if(err) {
         callback({err: err, message:"Error looking up company"});
      }
      else {
         console.log(gdoc); //Should print all the matching documents since gdoc is an array
         callback(null, gdoc.map(doc => doc.companies); //returns every companies of every document
      }
});

This time you can call Find with no parameters and chain the where statement like this

Group.find({}).where('_id').in(grArr).exec(callback)

Upvotes: 2

Lemix
Lemix

Reputation: 2950

find() passed array to the callback function. See documentation https://mongoosejs.com/docs/api.html#model_Model.find

gdoc is array. Edit your code like this:

...
callback(null, gdoc[0].companies);
...

Upvotes: 0

Related Questions