首页 > 解决方案 > 如何触发猫鼬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 触发。

标签: mongodbmongoose

解决方案


看起来Pre中间件功能中有错字。根据我们的 Schema,键名是updatedAt,但在函数中,它被称为updated


推荐阅读