How would I return the order of MongoDB Posts by t

2019-09-19 04:02发布

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}});

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} });

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.

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.

Note: Oddly MongoDB seems to record the quotes in the order they were favourited, but it doesn't retrieve them that way, if I leave out the sort option.

1条回答
仙女界的扛把子
2楼-- · 2019-09-19 04:42

Instead of just recording what posts a user likes with:

Meteor.users.update({ _id: this.userId },{ $addToSet: { liked: 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() }});

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.

查看更多
登录 后发表回答