0

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.

4
  • 1
    find query returns array. So here gdoc is an array you either need to loop over the gdoc and console the values or console gdoc[0].companies Commented Sep 26, 2018 at 17:13
  • With MongoDB it's easiest to first use queries in the console to see whether or not they work, you don't have to run anything and stdout/stderr is directly there Commented Sep 26, 2018 at 17:14
  • @Anthony Is there any other way where it will return all the ids but not in array. Thank yoi. Commented Sep 26, 2018 at 18:05
  • Could you explain what you really need? Commented Sep 26, 2018 at 18:24

3 Answers 3

2

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Yes, I was mixing both. It works great. I got the ids in array in this way -- var companies = [].concat(...gdoc.map(doc => doc.companies));
0

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);
...

2 Comments

If I have 2 elements in an array then it would be gdoc[0] and gdoc[1]. Any other way to avoid to run a loop of gdoc.
@PrithvirajMitra you are going to have to loop over them anyway
0

Try this,

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

}, (err) => {

});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.