猫鼬日期/时间戳有什么用?

时间:2018-03-09 14:22:57

标签: date mongoose timestamp

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

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();

})

1 个答案:

答案 0 :(得分:0)

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

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

相关问题