我正在尝试使用各种 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/