动态

详情 返回 返回

Mongoose無法更新時間戳 - 动态 详情

Mongose 是為 node.js 開發的 MongoDB 對象模型,它基於schema來處理應用的數據模型,開箱即用。

schema中的時間戳

const mongoose = require('mongoose');

const BlogSchema = new mongoose.Schema({
  id: { type: Number },
  title: { type: String },
  category: { type: String },
  tags: { type: String },
  abstract: { type: String },
  content: { type: String },
  creator: { type: String },
  status: { type: Number },
  top: { type: Number, default: 1 }, // 1. 非置頂 2. 置頂
  view_count: { type: Number },
}, {
  timestamps: {
    createdAt: 'create_time',
    updatedAt: 'update_time',
  },
});

如上定義的BlogSchema,timestamps可以幫助我們在創建新的數據(或者更新)時自動維護創建時間和更新時間。

那麼問題來了

然而,當我們想要更新創建時間時會遇到無法更新的問題(雖然很少有人會更新創建時間...)。

查閲Mongoose官網,在這裏找到了答案:

// Mongoose blocked changing createdAt and set its own updatedAt, ignoring
// the attempt to manually set them.

意思是如果我們開啓了自動生成時間戳,那麼當我們使用findOneAndUpdate(), updateMany(),updateOne()這些方法更新 create_time 是不會生效的,會被Mongoose忽略。

解決方法

const mongoose = require('mongoose');

const BlogSchema = new mongoose.Schema({
  id: { type: Number },
  title: { type: String },
  category: { type: String },
  tags: { type: String },
  abstract: { type: String },
  content: { type: String },
  creator: { type: String },
  status: { type: Number },
  top: { type: Number, default: 1 }, // 1. 非置頂 2. 置頂
  view_count: { type: Number },
  create_time: { type: Date, default: Date.now }
}, {
  timestamps: {
    // createdAt: 'create_time',
    createdAt: false,
    updatedAt: 'update_time',
  },
});

在Schema字段中增加了最後一行 create_time: { type: Date, default: Date.now }

timestamps 中 createdAt: false, 表示不自動生成時間戳,我們手動維護。而 update_time 還是由Mongoose替我們維護。

這樣,再次嘗試更新時,create_time就會被設置為你期望的值。

文章首發於 IICOOM-個人博客 《Mongoose無法更新時間戳》

user avatar alibabawenyujishu 头像 razyliang 头像 wmbuke 头像 aresn 头像 zhaodawan 头像 gaozhipeng 头像 xiao2 头像 junxiudetuoba 头像 13592899917 头像 infinilabs 头像 ruanjiankaifa_xiaofanya 头像 coderleo 头像
点赞 40 用户, 点赞了这篇动态!
点赞

Add a new 评论

Some HTML is okay.