如何将多个mongoose查询组合成一个

时间:2017-11-22 04:05:02

标签: node.js mongoose

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

如何将查询句子合并为一个并获得所有结果? ps:我使用mongoose来操作mongoDb。

1 个答案:

答案 0 :(得分:3)

您可以将所有查询包装在Promise.all()中以获得所需的结果。传递给Promise.all()的查询将同时执行。看看下面的代码。

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

如果您使用的是bluebird库,那么您可以使用Promise.props(),它基本上允许您传递对象而不是数组。

 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);
})
相关问题