Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute multiple queries at once in Mongoose

I am trying to combine two queries in Mongoose into one.

Right now, I'm doing this:

User.find({ _id: req.body.userId }, (err, user) => {
  User.find({ username: decodedUser.username }, (err, member) => {
   console.log("user\n", user)
   console.log("member\n", member)
 })
})

I'd like to make a single User.find() query to the database, and the result be an object (or an array) of all the documents that I want, such as an array of [user, member] in this case. This will save me from having to run User.find() twice. Ideally, I'd like the result from the query to be an object so that I can find a specific key/value set more easily, as opposed to an array that I would have to iterate through to find a particular element. How do I do this?

Note: this works:

User.find({ $or:
  [
    { _id: req.body.userId },
    { username: decodedUser.username}
  ]}, (err, results) => {
  console.log("results\n", results)
})

where results is an array of the documents that I want. But, I'd like to know if there is a better way.

like image 267
Farid Avatar asked Dec 11 '17 03:12

Farid


1 Answers

If you are expecting only one result by both of your conditions then you could use User.findOne - it will return the first found result.

User.findOne({ $or:
  [
    { _id: req.body.userId },
    { username: decodedUser.username}
  ]}, (err, user) => {
  console.log("user\n", user)
})

Edit

Since you said that you need to get 2 results and you want to have then in the result you can also run 2 queries in parallel and use promises to get the result. E.g.

Promise.all([
  User.find({ _id: req.body.userId }),
  User.find({ username: decodedUser.username})
]).then( ([ user, member ]) => {
  console.log( util.format( "user=%O member=%O", user, member ) );
});
like image 78
Zilvinas Avatar answered Sep 18 '22 12:09

Zilvinas