当前位置:网站首页>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就会被设置为你期望的值。
边栏推荐
猜你喜欢

Altium Designer Basics

【MQ-3 Alcohol Detector and Arduino Detect Alcohol】

【LeetCode】Add the linked list with carry

【LeetCode】合并

Process (in): process state, process address space

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

GM7150,振芯科技,视频解码器,CVBS转BT656/601,QFN32,替换TVP5150/CJC5150

unity学习(五):Excel表格读取和数据类生成

MPU6050 accelerometer and gyroscope sensor is connected with the Arduino

2020 - AAAI - Image Inpainting论文导读《Learning to Incorporate Structure Knowledge for Image Inpainting》
随机推荐
unity相关的功能链接
开源日志库 [log4c] 使用
分割回文串 DP+回溯 (LeetCode-131)
增量编译技术在Lightly中的实践
unity 代码拆分图集
R语言 —— 多元线性回归
本地数据库 sqlite3 编译和使用
进程(下):进程控制、终止、等待、替换
idea中创建jsp项目详细步骤
Basic IO (below): soft and hard links and dynamic and static libraries
rosdep update失败解决办法(亲测有效)
Altium Designer Basics
DMA相应外设映射
振芯GM7123C:功能RGB转VGA芯片方案简介
【详解】线程池及其自定义线程池的实现
Comparative analysis of OneNET Studio and IoT Studio
【网络基础】浏览器输入一个URL之后,都发生了什么(详细讲解)
【LeetCode】链表相加 进位
【面试必看】链表的常见笔试题
振芯科技GM8285C:功能TTL转LVDS芯片简介