I'm working on a small application and I need to automatically add a timestamp of creating/updating my documents in the default Nodejs MongoDb driver. Right now, when I add a new document, it only has added the _id field. Is there a way to force the addition of the createdAt/updatedAt fields?
You can add createdAt manually when creating the object this way:
await this.collection.insertOne({ businessAuth: _id, url, labels, createdAt: new Date()});
And updatedAT when updating the object this way:
video.updatedAt = new Date();
const saved = await this.collection.findOneAndUpdate({_id: video._id}, {$set: {...video}});
Drivers do not generally provide this functionality. ODMs do. In case of Node, mongoose is an ODM which does.