You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MongoDB+JavaScript:已购产品过期校验与有效数据筛选实现

解决已购课程过期校验与有效数据查询问题

首先要修正你存储数据时的一个关键错误:当前代码里expirationDate: \courseExpires``是把字符串"courseExpires"存进数据库了,而不是实际的日期对象。这会导致后续无法正确比较过期时间,先把存储代码改对:

let currentDate = new Date();
// 直接计算90天后的日期,不用转毫秒再转回来,更简洁
let courseExpires = new Date(currentDate.setDate(currentDate.getDate() + 90));

let userPurchasedCourses = new usersPurchasedCourses({
  username: `${value_a}`,
  coursesList: JSON.parse(value_c.replaceAll(".", '"')),
  expirationDate: courseExpires, // 去掉反引号,直接传Date对象
  tran_date: tran_date,
  status: "VALID"
});
await userPurchasedCourses.save();

查询未过期的有效数据

修改查询条件,添加对expirationDate的过滤,只保留当前时间小于过期时间的记录,同时结合原有的用户名和状态条件:

const now = new Date();
let userCourses = await usersPurchasedCourses.find({
  username: req.body.username,
  status: "VALID",
  expirationDate: { $gt: now } // $gt表示大于当前时间,即未过期
});

可选:批量标记已过期数据为无效

如果需要把已经过期的记录状态更新为"INVALID",可以用以下批量更新操作:

const now = new Date();
await usersPurchasedCourses.updateMany(
  {
    status: "VALID",
    expirationDate: { $lte: now } // $lte表示小于等于当前时间,即已过期
  },
  { $set: { status: "INVALID" } }
);

这样之后,你再查询status: "VALID"的记录时,就只会包含未过期的有效数据了。

内容的提问来源于stack exchange,提问作者Manas S. Roy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 12:40:25