【发布时间】:2017-06-19 09:30:02
【问题描述】:
我正在尝试从数据库中查询所有帖子,然后获取属于每个帖子的所有 cmets,并将整个内容发送回前端进行显示。到目前为止,我的策略一直是使用嵌套的 Mongoose 查询(请参阅下面的伪代码和实际代码示例),并且由于异步问题而得到了一些意想不到的结果。
谁能告诉我哪里出错了,或者是否有更好的方法来完成我想要完成的工作:
我的架构:
我在 Mongoose 中有三个 Schemas:
- 用户架构 (
User) - PostSchema (
Post) - CommentSchema (
PostComment)
我在这里只包含了CommentSchema,以简化我的问题:
var CommentSchema = new mongoose.Schema (
{
message: {
type: String,
minlength: [2, 'Your comment must be at least 2 characters.'],
maxlength: [2000, 'Your comment must be less than 2000 characters.'],
required: [true, 'You cannot submit an empty comment.'],
trim: true,
}, // end message field
userID: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
},
username: {
type: String,
},
postID: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Post'
},
},
{
timestamps: true,
}
);
创建新评论时,帖子的_id 会记录到评论的.postID 字段中。
我的伪代码策略:
// query for all posts using a mongoose promise
// run a `for loop` through the array returned posts
// query my comments collection for any comments pertaining to post[i]
// attach comments returned to the post[i]
// push post[i] into a new array (now with comments attached)
// check if on last run through array
// res.json the new array back to the front end
// On front end just iterate through each post and its contained comments.
但是,当我尝试这种策略时,我在 for 循环中的第二个 Mongoose 查询遇到了一些异步问题。
我的实际代码示例:
Post.find({}) // first query
.then(function(allPosts) {
for (var i = 0; i < allPosts.length; i++) {
_post = allPosts[i];
console.log(_post, i);
PostComment.find({postID: _post._id}) // **nested query
.then(function(comments) {
console.log({
post: _post, // this value will not match the console log above (outside of the query)
index_value: i, // this value too will be out of match with the console log above
comments: comments,
});
// attach new comment to allPosts[i]
// push post with comment attached to new array
// check if on last iteration, if so res.json new array
})
.catch(function(err) {
console.log(err);
})
}
.catch(function(err) {
console.log(err);
}
上述代码示例的问题:
在上面的示例中,在第二个查询中,**nested query、i 和 _post 的值在从 mongoose 承诺(.then)返回数据时不同步。 for 循环的进度比返回的数据快。因此,如果我尝试将任何 cmets 附加到父帖子对象 (_post),则该变量已经与 for 循环的进程不同步(_post 现在成为数组中的下一个帖子)。我很难解决如何解决这个问题并从每个帖子中获取我所有的 cmets,并将其捆绑在一起作为前端。我只是在这一点上感到困惑。
期望的行为:
我想要一个包含所有帖子的填充列表,每个帖子都附有 cmets,以便在前端更轻松地迭代它们。这样在前端,所有帖子都显示在其下方,并带有各自的 cmets。
结论:
我做错了什么?我如何遍历我的所有帖子,并为每个帖子获取所有 cmets,并使其在 Angular 中的前端显示中保持整洁?在我的查询中,我的方法是错误的还是太“昂贵”?有没有更好的方法来实现我想要的行为?
感谢您超越的任何见解或帮助!我四处搜索希望看到另一个这样的问题,并且在这个问题上已经有一段时间了=)
【问题讨论】:
标签: angularjs mongoose one-to-many mean-stack