iRo*_*tia 0 mongoose mongodb node.js express
updated_at每当数据库数据更新时,我们如何更改值
认为这是我的猫鼬模式,
const mongoose = require('mongoose')
const locationDataSchema = new mongoose.Schema({
locationName: String,
location: [{
lat: Number,
lng: Number
}],
news: [ {
author: String, //or number
title: String,
description: String,
url: String,
urlToImage: String
}],
updated_at: {
type: Date,
default: Date.now
}
})
Run Code Online (Sandbox Code Playgroud)
根据我对 Mongoose Docs 的模糊阅读,我做了这样的事情
locationDataSchema.post('save', (next) => {
console.log("here")
this.locationName = this.locationName.toLowerCase();
this.updated_at = Date.now()
})
Run Code Online (Sandbox Code Playgroud)
但每当我在猫鼬模式中创建/更新某些内容时,都不会调用此函数
问题:有人可以帮我弄清楚我该如何改变吗?
updated_at = Date.now()
Run Code Online (Sandbox Code Playgroud)
每当用户更新数据库中的数据时(同样将位置名称更改为小写)
当前版本的 Mongoose (v4.x) 将时间戳作为模式的内置选项:
var mySchema = new mongoose.Schema( {name: String}, {timestamps: true} );
此选项添加了带有日期时间戳的createdAt和updatedAt属性,它会为您完成所有工作。更多请查看
https://mongoosejs.com/docs/guide.html#timestamps
| 归档时间: |
|
| 查看次数: |
716 次 |
| 最近记录: |