MongoDB 存 Date,Redux 存 number

1. MongoDB Schema / 插入

假设你有一个用户表(user_profiles),存储时这样做:

// 写入时:前端拿到时间戳 (ms)

const createdAtTs = Date.now();  // e.g. 1755381000000

// 存到 MongoDB 时转成 Date

await db.collection("user_profiles").insertOne({

id: "u123",

createdAt: new Date(createdAtTs), // 存 Mongo Date 类型

});

👉 存进去后,MongoDB Compass / Atlas 后台会显示:

createdAt: 2025-08-17T02:30:00.000Z

(直观、可读)

2. 查询时转换给 Redux

当你从 MongoDB 拿出来时,字段是 Date 对象:

const doc = await db.collection("user_profiles").findOne({ id: "u123" });

const userProfile = {

id: doc.id,

createdAt: doc.createdAt.getTime(), // 转成 timestamp (ms)

};

dispatch({ type: "USER_LOADED", payload: userProfile });

👉 Redux 里会存:

{

"id": "u123",

"createdAt": 1755381000000

}

3. 前端展示

展示时再转回 Date:

const createdAt = new Date(user.createdAt);

{createdAt.toLocaleString()}

4. 整体规范

  • 数据库层(MongoDB):始终存 Date 类型(方便查询和后台直观)。
  • 接口层(API / Redux):统一转成 number(毫秒 timestamp)。
  • 展示层(UI):再 new Date(number) 转换。

这样三个层面都不冲突:

  • 数据库好看、好查。
  • Redux 简洁、序列化安全。
  • 前端展示灵活。