Home > Software design >  How to get mongo documents created in the last 24 hours using mongoose?
How to get mongo documents created in the last 24 hours using mongoose?

Time:04-29

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?

CodePudding user response:

const previousDay = new Date();
previousDay.setDate(previousDay.getDate() - 1);
Picture.find({ 
  user: new Types.ObjectId(userid),
  createdAt: {$gte: previousDay}
});

CodePudding user response:


const picturesInLast24Hours = Picture.find({
  user: new Types.ObjectId(userid),
  createdAt:{$gte: new Date(Date.now() - 24*60*60*1000)},
  // additional filters...
})

  • Related