当前位置:网站首页>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就会被设置为你期望的值。
边栏推荐
- Comparative analysis of OneNET Studio and IoT Studio
- 剑指Offer 31.栈的压入、弹出
- 【 LeetCode 】 design list
- Beckhoff ET2000 listener use
- Comparative analysis of mobile cloud IoT pre-research and Alibaba Cloud development
- Industry where edge gateway strong?
- 振芯GM7123C:功能RGB转VGA芯片方案简介
- 【面试必看】链表的常见笔试题
- UKlog.dat和QQ,微信文件的转移
- 使用buildroot制作根文件系统(龙芯1B使用)
猜你喜欢

Chrome 里的小恐龙游戏是怎么做出来的?

STM32 CAN 介绍以及相关配置

Basic IO (below): soft and hard links and dynamic and static libraries

【nRF24L01 connects with Arduino to realize wireless communication】

基础IO(下):软硬链接和动静态库

Altium Designer Basics

R语言 —— 多元线性回归

谷粒商城10——搜索、商品详情、异步编排

【Connect the heart rate sensor to Arduino to read the heart rate data】

同时求最大值与最小值(看似简单却值得思考~)
随机推荐
引擎开发日志:重构骨骼动画系统
Process (in): process state, process address space
unity 代码拆分图集
引擎开发日志:集成Bullet3物理引擎
GM8775C MIPI转LVDS调试心得分享
uniCloud use
全排列 DFS
引擎开发日志:场景编辑器开发难点
剑指Offer 32.Ⅰ从上到下打印二叉树
振芯科技GM8285C:功能TTL转LVDS芯片简介
学习(四):显示FPS,和自定义显示调试
AD Actual Combat
bluez5.50+pulseaudio实现蓝牙音响音频播放
2019 - ICCV - 图像修复 Image Inpainting 论文导读《StructureFlow: Image Inpainting via Structure-aware ~~》
进程(番外):自定义shell命令行解释器
本地数据库 sqlite3 编译和使用
Process (present) : custom shell command line interpreter
剑指Offer 04.二位数组中的查找 线性查找
LL(1)文法 :解决 if-else/if-else 产生式二义性问题
剑指Offer 34.二叉树中和为某一值的路径 dfs+回溯