mongodb - 如何触发猫鼬updateAt
问题描述
当数据发生变化时,我需要更新我的模型。可悲的是,这似乎行不通。
const mongoose = require('mongoose');
const moment = require('moment');
const Schema = mongoose.Schema;
const SomeSchema = new Schema({
query: String,
data: Object,
userId: String,
// Date.now() does work. I'm working with existing code.
createdAt: { type: Date, default: moment().format() },
updatedAt: { type: Date, default: moment().format() }
});
// Not sure why I need this
// Have also used 'save' instead of 'updateOne'
SomeSchema.pre('updateOne', function(next) {
this.updated = Date.now();
// this.updatedAt = Date.now() does not work either.
return next();
});
mongoose.model('someModel', SomeSchema);
实际使用:
const mongoose = require('mongoose');
const Model = mongoose.model('someModel');
// Ideally, I wanted something like "Model.findOrCreate" but... cant see that
const obj = {..};
// Im happy nothing will error here with this.
// Would love to use "findOrCreate" instead.
const data = await Model.updateOne({ ...obj });
// I hate this so much... by hey.
if (data.n === 0) {
// Create
Model.create({...obj}).save
}
我只是说,如果数据在那里,更新它,如果没有,创建它。但是我的updatedAt
密钥根本没有更新。它与createdAt
. 根据文档,我看不出我会如何$set
在这里使用。
主要是在找到数据updatedAt
时触发。
解决方案
看起来Pre
中间件功能中有错字。根据我们的 Schema,键名是updatedAt
,但在函数中,它被称为updated
。
推荐阅读
- dashboard - Sidemenu Node-red-dashboard 不可见
- node.js - 为什么 express.js 应用程序几乎总是在 nginx 或其他 Web 服务器之后?
- python - 检查数组是否包含numpy中的特定字符串
- jquery - 使用 shinyjs 切换表单水平输入及其标签
- wordpress - Wordpress 图像不再具有 srcset 并显示像素化图像
- elasticsearch - Elasticsearch - 如何从日期时间字段中提取日期并将其作为新字段添加到每个文档中
- python - importlib 中的方法具有相同的功能 imp.load_source
- pm2 - 我应该使用 pm2 的特殊用户来运行我的快速应用程序吗?
- c# - 为什么单击视图中的过滤器按钮时页面会刷新?
- sql - 我如何调试 SQL 子查询问题