如何获得在过去24小时内使用mongoose创建的mongo文档?



我有这个猫鼬模式

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...
})

最新更新