I have a Mongoose schema where I'm using the timestamps option to automatically add createdAt
and updatedAt
fields to documents. However, I want to apply timestamps only to the subdocuments, not to the main document.
Here's an example of my schema:
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,
}
);
The issue is that even though I've set timestamps: true
only for the subdocument schema, Mongoose is still adding timestamps to the main document, even though I disabled them.
Is there a way to configure Mongoose to apply timestamps only to the subdocuments within the feed
array and not to the main document?
The best way around this is - don't use Model.create()
to create your documents and instead use new Model()
combined with doc.save()
. That will allow you to pass in the {timestamps: false}
option when you call save()
. Here is an example:
const feedSchema = new mongoose.Schema(
{
userId: {
type: String,
required: true,
},
feed: [
new mongoose.Schema(
{
// ... (subdocument fields)
},
{ _id: false, timestamps: true } }
),
],
},
{
// _id: false, //< delete this
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 });
This will add the timestamps to the subdocuments but not on the parent document.
Note: you will need to delete the _id : false
on the parent schema as mongoose documents require an _id
before saving.