【问题标题】:Sort by comments and placing liked ones on top按评论排序并将喜欢的放在顶部
【发布时间】:2014-09-03 04:10:09
【问题描述】:

我有一个 Comments 数据库架构,如下所示:

Comments: {
    postId: '',
    body: '',
    upvotedBy: [],
    upvotes: 0
}

upvotedBy 保存了对其进行投票的用户的 UserId。 Upvotes 保存评论收到的总赞成票数。我的 Comments.find() 如下:

return Comments.find({ 
    'postId': this._id 
}, { 
    sort: { 
        'submitted': -1
    }
});

所以我正在寻找添加到排序位的内容,以在 upvotedBy 数组中查找当前登录用户的 Id,如果是,则以当前投票的评论的方式对列表进行排序用户首先列出。这可能吗?模糊地寻找类似的东西:

..
    sort: { 
        'submitted': -1,
        'upvotedBy' as upvotedByUser: checkIfInArray(userId)
    }
..

【问题讨论】:

    标签: mongodb meteor iron-router


    【解决方案1】:

    一种解决方案是获取两组文档:包含当前用户的 cmets 的文档和不包含的文档。如果每个集合都按submitted 排序,那么您只需连接结果。例如:

    var userId = Meteor.userId();
    var sort = {sort: {submitted: -1}};
    
    var myComments = Comments.find({
      postId: this._id,
      upvotedBy: userId
    }, sort).fetch();
    
    var otherComments = Comments.find({
      postId: this._id,
      upvotedBy: {$ne: userId}
    }, sort).fetch();
    
    myComments.concat(otherComments);
    

    【讨论】:

    • 哦,所以 mongo 会自动在数组中搜索吧?现在,如果我没有在 find() 之后添加 fetch(),最后一行会抛出错误“模板助手中的异常:TypeError: undefined is not a function”。如果我添加 fetch() ,我看不到任何结果:/
    • 在这两种情况下你都需要fetch,因为你需要2个数组(不是游标)。确保return myComments.concat(otherComments);。如果这不起作用,请尝试对每个中间结果进行console.log
    • 啊,笨蛋。是的,这是回报。现在可以工作了,尽管必须反过来:返回 otherComments.concat(myComments) 以将喜欢的放在首位。我之前的另一个解决方法是将这两个调用作为单独的模板助手,我在模板中有 {{#if postsWithLikes}} 和 {{# posts}}。感谢您的帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-22
    • 1970-01-01
    • 2013-05-26
    • 1970-01-01
    • 1970-01-01
    • 2016-03-24
    • 1970-01-01
    相关资源
    最近更新 更多