如何使用 mongoose 获取最近 24 小时内创建的 mongo 文档?

How to get mongo documents created in the last 24 hours using mongoose?

我有这个猫鼬模式

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);

这是生成文档的示例

{
        "_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
}

了解用户,如何获取特定用户最近24小时创建的所有文档?

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

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