9

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.

1 Answer 1

27

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

5 Comments

Thanks for the reply. I'm actually expecting two results. The end goal is to run two User.find() queries in one execution, rather than executing User.find() twice as in my example above, if that makes sense.
Then your solution looks the best to me
Yes! Your "Edit" is exactly what I've been trying to do. Oh man, thank you!
Out of curiosity, what does your last line, console.log( util.format( "user=%O member=%O", user, member ) );, do? Just tried running it locally, and nothing was outputted in my terminal. Specifically, I'm not really familiar with util.format.
You need to have const util = require('util'); this is a standard NodeJS utility service. Check the docs here: nodejs.org/api/util.html

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.