首页 > 解决方案 > 检索所有“日期”在过去 6 分钟内的人

问题描述

我有一个Product存储在 MongoDB 中的集合。它有一个属性date

const productSchema = new mongoose.Schema<ProductAttrs>({
    date: {
        type: Date, 
        required: true,
    }
    ...
})

我想检索date与当前时间相比在过去 6 分钟内的所有产品。在 mongoose 中检索它的有效方法是什么?

我在我的项目中使用 express.js + typescript + mongoose v5.11。

标签: node.jstypescriptmongodbexpressmongoose

解决方案


您必须使用 Mongoose 搜索每个时间大于 的记录now - 6 minutes
我无法测试它,但查询应该是这样的:

const sixMinutes = (6*60*1000); // 6 minutes
let sixMinutesAgo = new Date();
sixMinutesAgo.setTime(sixMinutesAgo.getTime() - sixMinutes);

const products = Product.find({ 
  date: {
        $gte: sixMinutesAgo
        }
  })

推荐阅读