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 usenew Model()combined withdoc.save(). That will allow you to pass in the{timestamps: false}option when you callsave(). Here is an example:This will add the timestamps to the subdocuments but not on the parent document.
Note: you will need to delete the
_id : falseon the parent schema as mongoose documents require an_idbefore saving.