javascript - 难以循环 Mongoose 数据

标签 javascript node.js mongodb mongoose

我正在尝试使用各种 mongoDB 文档填充一系列帖子。

app.get('/dash/:id', isLoggedIn, (req, res) => {
    var posts = [];
    User.findById(req.params.id, (err, user) => {
      user.follows.forEach((followId) => {
        User.findById(followId, (err, follow) => {
          follow.posts.forEach((postId) => {
            Post.findById(postId, (err, post) => {
              posts.push(post);
            })
          })
        })
      })
    })
    console.log(posts)
  })

我的问题是最终的 console.log 生成一个空数组,但是如果我在将每个文档推送到数组后立即调用 console.log(posts) ,一切都会正常工作。我确信我错过了一些愚蠢的东西。它是否在完成数据查找之前运行我的console.log?提前致谢!

最佳答案

mongoose 的 finById 是异步的,代码在获取数据时会执行其他内容(如 console.log ),但它返回一个 promise ,因此请利用它并避免您遇到的回调 hell ,并且您可以使用带有条件的 find() 而不是在循环中多次调用 findById()

我不知道你的架构是什么样的,但理想情况下你会使用 populate 来避免第二个 .find() ,并且可能会向 posts 添加一个 ref 但这里是基于你的帖子的建议:

试试这个:

app.get('/dash/:id', isLoggedIn, (req, res) => {

    User.findById(req.params.id).select('follows -_id') // this will return an array of follows
    .then((follows) => {
        return User.find({ _id : follows}).select('posts -_id') // this will retrun an array of posts Ids
    })
    .then((postsIds) => {
        return Post.find({ _id : postsIds}); // these are your posts        
    })
    .then((posts) => {
        console.log(posts); // do stuff with posts here, res.render() maybe ?
    })

});

关于javascript - 难以循环 Mongoose 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49837272/

相关文章:

javascript - 如何使用查询参数来限制 Google Contacts API 中检索到的联系人

javascript - 为什么 twitter bootstrap 的 typeahead 在这里不起作用?

node.js - Amazon Redshift Node 并行请求比顺序请求花费的时间更长

node.js - Express js 模块化 REST 框架

javascript - 返回 mysql 查询的结果。最终返回 undefined

javascript - 如何查看javascript HTML5 localstorage?

node.js - 静态模式方法: Cannot read property 'myFindOrCreate' of undefined

c++ - 新的 C++ Mongo 驱动程序 : how to see type and how to get string value

java - 从java到mongo db的数据访问有什么推荐的模式或策略吗?

mongodb - mongodb - 用于在网络应用程序中实现类似功能的模式