有没有办法在猫鼬模式中有选择地应用时间戳?

Is there a way to selectively apply timestamps in mongoose schema?

我目前正在设计猫鼬架构。该架构用于博客评论,如下所示:

new mongoose.Schema({
  commentedOn: {
    type: mongoose.Schema.Types.ObjectId,
    required: true
  },
  author: {
    type: String,
    required: true
  },
  contents:{
    type: String
  },
  points: {
    type: Number,
    default:0
  },
  timestamps: true
})

积分栏是记录一条评论的得票数。我不想每次用户对评论进行投票时都更改时间戳。有没有办法做到这一点?或者我应该将 points 字段移出这个模式吗?

我认为 timestamps 应该在 second argument of the schema 中通过。

关于你的问题,我能想到的唯一方法是不使用 timestamps 并明确声明你的时间戳字段,例如createdAtupdatedAt 在您的架构中。每当您保存或更新时,您都会根据情况显式设置(或不设置)updatedAt 字段。

new mongoose.Schema({
    commentedOn: { type: mongoose.Schema.Types.ObjectId, required: true },
    author: { type: String, required: true },
    contents: String,
    points: { Number, default: 0 },
    createdAt: { type: Date, default: Date.now },
    updatedAt: Date
});