Jesus_Maria
Jesus_Maria

Reputation: 1207

Mongoose, how to do a find() with two or more parameters

i have such example:

http://host.com/entries?users[0]=steve&users[1]=edward

This query should give me only users with such names

I have do such code

exports.find = (req, res, next) ->
  e = req.query.entries

  if hosts
    e = ({$or: [{entry}]} for entry in e)

    Collection.find {active: true}
    $and: e
    .exec (err, results) ->
      console.log results
      res.json results

But it returns me empty list How I can use mongoose in correct way?

Upvotes: 0

Views: 2208

Answers (1)

Roman Sachenko
Roman Sachenko

Reputation: 668

You may use $in operator to search from array.

Example: you have an array of names like var names = ['Foo', 'Bar', 'Baz' ]

Resolution:

Callback

var searchQuery = {name: {$in: names}};
UserModel.find(searchQuery, function(err, foundUsers){
  if(err){
    //do something with err
  } else {
    //do something with foundUsers
  }
});

Promise

var searchQuery = {name: {$in: names}};
UserModel
  .find(searchQuery)
  .exec()
  .then(function(foundUsers){
    //do something with foundUsers
  })
  .onReject(function(err){
    //do something with err
  });

As for parameters in your query, you may add them as many as you want just like adding new keys into JSON object:

var searchQuery = {
  'foo': 'bar',
  'baz': 'qux'
};

Upvotes: 1

Related Questions