头图
Mongose is a MongoDB object model developed for node.js, which is based on the schema to handle the data model of the application, out of the box.

timestamp in 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 as defined above, timestamps can help us automatically maintain the creation time and update time when creating new data (or updating).

Then here comes the problem

However, when we want to update the creation time, we run into the problem of not being able to update it (although very few people will update the creation time...).

Check the Mongoose official website and find the answer here:

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

It means that if we turn on automatic timestamp generation, then when we use findOneAndUpdate() , updateMany() , updateOne() these methods to update create_time will not take effect and will be updated by Mongoose ignores.

Solution

 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',
  },
});

Added last line in Schema field create_time: { type: Date, default: Date.now }

createdAt: false in timestamps means that timestamps are not automatically generated, and we maintain them manually. And update_time is still maintained by Mongoose for us.

This way, when you try to update again, create_time will be set to the value you expect.

The article was first published on IICCOM-personal blog "Mongoose cannot update timestamp"


来了老弟
508 声望31 粉丝

纸上得来终觉浅,绝知此事要躬行