当前位置:网站首页>Mongoose无法更新时间戳
Mongoose无法更新时间戳
2022-08-02 03:34:00 【IICOOM】
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就会被设置为你期望的值。
边栏推荐
猜你喜欢
随机推荐
2020 - AAAI - 图像修复 Image Inpainting论文导读 -《Region Normalization for Image Inpainting》
Basic IO (on): file management and descriptors
剑指Offer 04.二位数组中的查找 线性查找
Typora use
逆序对数量与归并排序
判断回文
【plang 1.4.3】定时器的使用
进程(番外):自定义shell命令行解释器
字符串匹配(蛮力法+KMP)
proteus数字电路仿真——入门实例
倒排单词
引擎开发日志:场景编辑器开发难点
Industry where edge gateway strong?
【LeetCode】设计链表
AD实战篇
Host your own website with Vercel
最长连续不重复子序列 双指针
Application of electronic flow on business trip
进程(下):进程控制、终止、等待、替换
Basic IO (below): soft and hard links and dynamic and static libraries









