【问题标题】:Timestamp for specific property - Mongoose特定属性的时间戳 - Mongoose
【发布时间】:2021-12-25 11:51:27
【问题描述】:

我需要获取上次属性“已发布”从“假”变为“真”或反之亦然的时间戳,并且我需要具有 createdAt 和 updatedAt 属性。因此,我将 timestamps: true 传递给 Mongoose 模型配置,如果 createdAt 和 updatedAt 属性一切正常。

我不知道,所以我需要你的帮助,如何获取属性 publishedAt 和 unpublishedAt 的时间戳。这是我的 Mongoose 模型,您可以在其中看到所有内容。

如果您需要任何其他信息,请写下 im cmets 部分。

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const offerSchema = new Schema({
    title: {
        type: String,
        required: true,
        maxlength: 255
    },
    slug: {
        type: String,
        required: true,
        maxlength: 255
    },
    published: {
        type: Boolean,
        default: false
    },
    publishedAt: {
        type: Date
    },
    unpublishedAt: {
        type: Date
    },
    introduction: {
        type: String,
        required: true
    },
    description: {
        type: String,
        required: true
    },
    imageUrl: {
        type: String,
        required: true
    },
    authorId: {
        type: Schema.Types.ObjectId,
        ref: 'User'
    },
    sectionId: {
        type: Schema.Types.ObjectId,
        ref: 'Section'
    }
},  {
    timestamps: true
});

module.exports = mongoose.model('Offer', offerSchema);

【问题讨论】:

    标签: node.js mongodb express mongoose timestamp


    【解决方案1】:

    你想要的东西太定制了,Mongoose 不提供开箱即用的功能。

    但这不是问题,因为您可以自己实现它。您可以使用pre 挂钩运行一些自定义代码,然后每次更新您感兴趣的字段时,更新时间戳。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-10-09
      • 2017-01-18
      • 1970-01-01
      • 1970-01-01
      • 2012-10-28
      • 2017-11-18
      相关资源
      最近更新 更多