'How to get mongo documents created in the last 24 hours using mongoose?
I have this mongoose schema
const PictureSchema = mongoose.Schema({
user: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
required: true
},
title: {
type: String,
minLength: 3,
maxlength: 80,
required: true
},
//other fields
}, {timestamps: true} );
module.exports.Picture = mongoose.models.Picture || mongoose.model('Picture', PictureSchema);
this is an example of generated document
{
"_id" : ObjectId("6266a2a4d3df24b752800c77"),
"user" : ObjectId("6256946abe645f2e686cc3e3"),
"title" : "test upload",
//other fields
"createdAt" : ISODate("2022-04-25T13:31:16.303Z"),
"updatedAt" : ISODate("2022-04-25T13:31:16.303Z"),
"__v" : 0
}
knowing the user, how can I get all the documents created by a specific user in the last 24 hours?
Solution 1:[1]
const previousDay = new Date();
previousDay.setDate(previousDay.getDate() - 1);
Picture.find({
user: new Types.ObjectId(userid),
createdAt: {$gte: previousDay}
});
Solution 2:[2]
const picturesInLast24Hours = Picture.find({
user: new Types.ObjectId(userid),
createdAt:{$gte: new Date(Date.now() - 24*60*60*1000)},
// additional filters...
})
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | shubham |
