在嵌套文档上设置时间戳,但不在 Mongoose 中的父文档上设置时间戳

问题描述 投票:0回答:1

我有一个 Mongoose 模式,我使用时间戳选项自动将

createdAt
updatedAt
字段添加到文档中。但是,我只想将时间戳应用于子文档,而不是主文档。

这是我的架构示例:

const feedSchema = new mongoose.Schema(
  {
    userId: {
      type: String,
      required: true,
    },
    feed: [
      new mongoose.Schema(
        {
          // ... (subdocument fields)
        },
        { _id: false, timestamps: true } }
      ),
    ],
  },
  {
    _id: false,
    timestamps: false,
    versionKey: false,
  }
);

问题是,即使我只为子文档模式设置了

timestamps: true
,Mongoose 仍然向主文档添加时间戳,即使我禁用了它们。

有没有办法将 Mongoose 配置为仅将时间戳应用于

feed
数组中的子文档而不应用于主文档?

mongodb mongoose timestamp mongoose-schema subdocument
1个回答
0
投票

解决此问题的最佳方法是 - 不要使用

Model.create()
创建文档,而是将
new Model()
doc.save()
结合使用。这将允许您在调用
{timestamps: false}
时传入
save()
选项。这是一个例子:

const feedSchema = new mongoose.Schema(
  {
    userId: {
      type: String,
      required: true,
    },
    feed: [
      new mongoose.Schema(
        {
          // ... (subdocument fields)
        },
        { _id: false, timestamps: true } }
      ),
    ],
  },
  {
    _id: false,
    timestamps: false,
    versionKey: false,
  }
);

const Feed = mongoose.model('Feed', feedSchema);

const newFeed = {
   userId: '123',
   feed: [
      {
         a: 'abc',
         b: 'xyz'
      }
   ]
};

const doc = new Feed(newFeed);
await doc.save({ timestamps: false });

这会将时间戳添加到文档中,但不会添加到父文档中。

© www.soinside.com 2019 - 2024. All rights reserved.