node.js - 检索最近 6 分钟内所有 `date` 的内容

标签 node.js typescript mongodb express mongoose

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

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

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

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

最佳答案

您必须使用 Mongoose 搜索时间大于现在 - 6 分钟的每条记录。
我无法测试它,但查询应该如下所示:

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

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

关于node.js - 检索最近 6 分钟内所有 `date` 的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68419082/

相关文章:

javascript - 在 ng build angular 中运行严格编译

reactjs - 如何将react-hooks、redux和typescript结合在一起?

node.js - 基于 Mongoose 的应用架构

java - 通过Java中的SSH隧道连接到Mongo数据库

node.js - Mongoose - 使用 .populate 访问嵌套对象

node.js - 具有单个文档字符串数组字段的服务器端分页

node.js - 如何使用 Express + Docker + Azure 映射端口

node.js - 无法调用位方法

java - 在 Angular4 中渲染缩略图

typescript - 多个属性作为 typescript 中的索引签名