動態

詳情 返回 返回

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.