当前位置:网站首页>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就会被设置为你期望的值。
边栏推荐
猜你喜欢
随机推荐
向龙芯2K1000板子上烧写中标麒麟系统
Host your own website with Vercel
联阳(ITE)IT66021FN:HDMI转RGB芯片 3D 资料
Hash table problem solving method
笔记本电脑充电问题
unity相关的功能链接
联阳IT6561|IT6561FN方案电路|替代IT6561方案设计DP转HDMI音视频转换器资料
408-二叉树-先序中序后序层次遍历
AD8361检波器
与TI的lvds芯片兼容-GM8284DD,GM8285C,GM8913,GM8914,GM8905C,GM8906C,国腾振芯LVDS类芯片,
引擎开发日志:OpenGL资源多线程加载
剑指Offer 34.二叉树中和为某一值的路径 dfs+回溯
【plang 1.4.4】编写茶几玛丽脚本
change file extension
剑指Offer 31.栈的压入、弹出
Basic IO (below): soft and hard links and dynamic and static libraries
R语言 —— 多元线性回归
AD Actual Combat
Process (in): process state, process address space
NSIS来自己设定快捷方式的图标