我将如何按用户喜欢的时间返回 MongoDB 帖子的顺序? [英] How would I return the order of MongoDB Posts by time Favourited by user?

查看:50
本文介绍了我将如何按用户喜欢的时间返回 MongoDB 帖子的顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个网络应用,其中包含用户可以收藏或喜欢"的帖子.当他们收藏一个帖子时,postId 会被添加到 users 集合中的一个数组中.

I have a web app with posts that the user can Favourite or "Like". When they fav a post the postId gets added to an array in the users collection.

Meteor.users.update({_id:this.userId},{$addToSet:{liked:postId}});

我可以通过检索这个喜欢"的帖子数组并使用 $in 运算符来返回这些帖子.

I am able to return these posts by retrieving this array of "liked" posts and using the $in operator.

Posts.find({ _id: { $in: user.liked } }, 
  {sort: {upcount: -1, views: -1} });

目前,正如您所看到的,它们首先按 upcount(即收藏的数量)排序,然后按 views 排序.

At the moment as you can see they are being sorted firstly by the upcount which is just the number of favs, and then by views.

不过,我最终想要做的是按照用户喜欢帖子的时间对这些结果进行排序.我确定我必须在某处记录诸如 timeFavorited 之类的内容,但我不确定在哪里.

What I want to eventually do though, is sort these results by the time that the user favourited the post. I'm sure I will have to record something like timeFavourited or something similar somewhere, but I'm not sure where.

注意:奇怪的是 MongoDB 似乎按照他们最喜欢的顺序记录引号,但如果我省略排序选项,它不会以这种方式检索它们.

推荐答案

而不是仅仅记录用户喜欢的帖子:

Instead of just recording what posts a user likes with:

Meteor.users.update({ _id: this.userId },{ $addToSet: { liked: postId }});

推送一个包含 postId 和当前日期的对象

Push an object that includes both the postId and current date

Meteor.users.update({ _id: this.userId },
  { $push: { liked: { postId: postId, likedAt: new Date() }});

这解决了您的存储位置"问题,但它确实以其他方式使您的生活复杂化,因为您的搜索/排序查询将变得更加复杂.您还需要防止代码被欺骗,因为 $addToSet 会自动为您做到这一点 $push 不会.

That solves your "where to store" question but it does complicate your life in other ways because your search/sort query is going to be more complicated. You'll also need to prevent dupes with code because while $addToSet does that for you automatically $push does not.

这篇关于我将如何按用户喜欢的时间返回 MongoDB 帖子的顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆