【发布时间】:2021-03-05 05:38:03
【问题描述】:
当数据发生变化时,我需要更新我的模型。可悲的是,this 似乎不起作用。
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 保持一致。基于docs,我看不出我会如何在这里使用$set。
主要是触发updatedAt无论何时找到数据。
【问题讨论】: