skip to Main Content

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?

2

Answers


  1. const previousDay = new Date();
    previousDay.setDate(previousDay.getDate() - 1);
    Picture.find({ 
      user: new Types.ObjectId(userid),
      createdAt: {$gte: previousDay}
    });
    
    Login or Signup to reply.
  2. 
    const picturesInLast24Hours = Picture.find({
      user: new Types.ObjectId(userid),
      createdAt:{$gte: new Date(Date.now() - 24*60*60*1000)},
      // additional filters...
    })
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search