How would I return the order of MongoDB Posts by time Favourited by user?

半世苍凉 提交于 2020-01-25 10:59:16

问题


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:


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.



来源:https://stackoverflow.com/questions/32000889/how-would-i-return-the-order-of-mongodb-posts-by-time-favourited-by-user

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!