I have this article schema:
var article = new mongoose.Schema({
likes: [{
id: ObjectId,
by: {type: ObjectId, ref: 'User'},
created_at: {type: Date, default: Date.now}
}],
}, {timestamps: {createdAt: 'created_at'}});
on which I store the likes that the story gets. As you can see the field likes stores users who liked the article and the time they liked the story.
Now I want to query all the articles that got likes in the last 24 hours. How is that possible to do in Mongoose?
Sandeep Panda
co-founder, Hashnode
I suggest tweaking the schema a little bit. If you store all the "like" info in a nested array, your documents are going to grow over the time. MongoDB has 16MB limit on the document size. So, you can imagine the size of an article with thousands of likes! Imo, the better way is to introduce a junction collection which just stores the information about who liked what article:
var UserArticleLikes = new mongoose.Schema({ userId: {type: ObjectId, ref: 'User'}, articleId: {type: ObjectId, ref: 'Article'}, dateAdded: 'Date' });Now you can query all the articles that got likes within last 24 hours by running something like this:
db.userarticlelikes.find({ dateAdded: {$gt: currentTimestamp - 86400000 } })Note: The above query will give you duplicates. So, you need to take care of that.