Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to combine multiple mongoose query in to one

User.find().then(function (user) {
    console.log(user)
})
Category.find().then(function (category) {
    console.log(err);
})
Content.find().then(function (content) {
    console.log(content);
})

how can I combine the query sentences into one and get all result? ps: I use mongoose to operation mongoDb.

like image 774
Jolin Chen Avatar asked Nov 22 '17 04:11

Jolin Chen


1 Answers

You can wrap all of your queries inside Promise.all() to get the desired result. The queries passed to Promise.all() will be executed concurrently. Check out the code below.

Promise.all([
  User.find(),
  Category.find(),
  Content.find()
])
.then(results=>{

  //results return an array

  const [users,categories,content] = results;

  console.log("users",users);
  console.log("categories",categories);
  console.log("contents",content);

})
.catch(err=>{
  console.error("Something went wrong",err);
})

In case you are using bluebird library then you can use Promise.props(), which basically allows you to pass an object instead of an array.

 Promise.props({
    users:User.find(),
    categories : Category.find(),
    content : Content.find()
}).then(result=>{

    console.log("users",result.users);
    console.log("categories",result.categories);
    console.log("contents",result.content);

}).catch(err=>{
    console.error("Something went wrong",err);
})
like image 72
Ankit Bahuguna Avatar answered Oct 13 '22 00:10

Ankit Bahuguna