mongoose 如果已索引,则默认日期与流程启动日期相同

bxjv4tth  于 2023-01-26  发布在  Go
关注(0)|答案(1)|浏览(136)
var saleSchema = new Schema ({
  ...
  date: {type: Date, 'default': Date.now, index: true}
 ...
})

我尝试使用data()函数将当前日期放入数据库,但它与已索引的日期保持相同,并且每个下一个提交的日期与启动索引保持相同

avwztpqn

avwztpqn1#

你可以在模式的底部放置一个timestamps标志,这样,每次创建文档时,你都会得到创建日期-createdAt,每次修改文档时,你都会得到更新日期-updatedAt

const mongoose = require("mongoose");

const TaskSchema = new mongoose.Schema(
  {
    task: {
      type: String,
      required: [true, "Please enter a task name"],
    },
    info: {
      type: String,
      required: [true, "Please provide details for the task"],
    },
    due: {
      type: Date,
      required: [true, "Please provide a due date"],
    },
    complete: {
      type: Boolean,
      required: true,
      default: false,
    },
    createdBy: {
      type: mongoose.Types.ObjectId,
      ref: "User",
      required: [true, "please provide user"],
    },
  },
  { timestamps: true }
);

module.exports = mongoose.model("Task", TaskSchema);

在上面的示例中,您可以看到时间戳标志被设置为true,因此当您搜索任务文档时,您将得到如下内容:

相关问题