猫鼬日期/时间戳是怎么回事?



我有问题。我一直在尝试 2 种不同的方法来在将项目添加到集合后获得正确的日期。

1. new Date()
2. Date.now()

这两个示例都有相同的问题。只有第一个添加的文档才具有正确的日期。下一个具有完全相同的日期。为什么日期没有改变?

这是我的收藏:

const commentSchema = new Schema({
    author: {
    type: Schema.Types.ObjectId,
    ref: 'user'
  },
  addDate: {
    type: Date,
    default: Date.now()
  },
  content: String,
  answers: [commentReplies],
  articleID: {
    type: Schema.Types.ObjectId,
    ref: 'article'
  }
});

我的插入码:

app.post('/api/comments/addComment', async (req, res) => {
const author = req.body.author,
      content = req.body.content,
      articleID = req.body.articleID;
const comment = await new Comment({
  author, content, articleID
}).save().catch(err => {
  console.log(err);
})
res.send();

}(

因为这样做猫鼬使用创建模式时的日期:它执行Date.now()函数并将该值用作每个文档的默认值。

可能更好的方法是使用保存钩子并在钩子中以编程方式设置日期。

最新更新