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

如何为汽车模型配置双属性时间序列?TypeScript实现疑问

解决方案:按时间维度记录车辆购车价格

你的当前实现只能存储单次购车价格和对应日期,要实现按时间维度记录历史价格,需要把价格和日期的组合改成数组形式,用来存储每一次的价格变动记录。以下是调整后的TypeScript + Mongoose配置:

1. 定义价格历史的类型与Schema

先单独定义价格历史的结构,让代码逻辑更清晰:

// 价格历史条目类型
export type PriceHistory = {
  price: number;
  date: Date;
};

// 对应的Mongoose Schema
const PriceHistorySchema = new Schema<PriceHistory>({
  price: { type: Number, required: true },
  date: { type: Date, default: Date.now, required: true }
});

2. 修改Car模型的类型与Schema

把原来的buyPrice和buyPriceDate替换为priceHistory数组;如果需要快速获取最新价格,可以额外保留currentBuyPrice字段:

// 修改后的Car类型
export type Car = {
  _id: string;
  code: string;
  // 可选:快速获取最新价格,避免每次从数组取最后一项
  currentBuyPrice?: number;
  // 价格历史数组,存储所有时间维度的价格记录
  priceHistory: PriceHistory[];
};

// 修改后的Car Schema
const CarSchema = new Schema<Car>(
  {
    code: { type: String, required: true },
    currentBuyPrice: { type: Number, required: false },
    priceHistory: [PriceHistorySchema] // 嵌入价格历史Schema
  },
  {
    timestamps: true,
  },
);

export default model('Car', CarSchema);

3. 新增价格记录的示例操作

添加新购车价格时,用Mongoose的$push操作符往数组追加记录,同时可同步更新currentBuyPrice:

// 给指定id的车辆添加新价格
await Car.findByIdAndUpdate(
  carId,
  {
    $push: { priceHistory: { price: 150000 } }, // date自动使用当前时间
    $set: { currentBuyPrice: 150000 }
  },
  { new: true } // 返回更新后的文档
);

说明

  • 数组结构可以完整保留每一次价格变动的时间点和对应价格
  • date字段设置default: Date.now,新增记录时无需手动传入时间
  • currentBuyPrice是优化查询效率的可选字段,不需要的话可以直接删除

内容的提问来源于stack exchange,提问作者Mediator

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 16:23:29