Reputation: 437
I am trying to save every version of the whole document on every save to list all the versions on my frontend, what is the best solution to handle this ?
Upvotes: 0
Views: 1512
Reputation: 522
You don't need to keep the same _id (ObjectId) you can just duplicate the content and connect the old version to the new version by id.
const Example = new Schema({
// your stuff
oldVersion: {
mongoose.ObjectId,
ref: 'Example'
}
});
Then you could intercept the update command and create a new document with the old version and update the with the new version.
Example.pre(['updateOne', 'findOneAndUpdate'], async function(next) {
let doc = await Example.findOne(this.getFilter(), {
_id: 0
});
await Example.create(doc)
next();
});
Checkout this part of the documentation https://mongoosejs.com/docs/api.html#schema_Schema-pre for the interceptor and this for the reference https://mongoosejs.com/docs/api.html#schematype_SchemaType-ref
Upvotes: 2