【问题标题】:How to trigger a mongoose updatedAt如何触发猫鼬updateAt
【发布时间】: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无论何时找到数据。

【问题讨论】:

    标签: mongodb mongoose


    【解决方案1】:

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

    【讨论】:

    • 嗨。是的。我也试过this.updatedAt,但还是一样。
    猜你喜欢
    • 2015-10-08
    • 2023-03-15
    • 2013-08-05
    • 2018-06-09
    • 1970-01-01
    • 2017-08-24
    • 2015-05-14
    • 1970-01-01
    • 2020-10-11
    相关资源
    最近更新 更多