Keep track of changes

Hello :smiley:, I am working on a project with mongoDB. One of the fields of my collections is called locked_props and is of type [string] in which I want to store the names of the fields that are updated from forest.

Is there any possibility to achieve this?

For example I have my Users collection in which the fields are First name, Last name, Email and Locked_props. If in forest I update the name, for example I change from usr1 to user1, I would like to add to the locked_props field “name”.

Is there any way to achieve this?
thank you for your help!
Thank you!

Hi @usr1vang,

Yes you can using mongoose hooks:

UsersSchema.pre('save', function() {
  // modifiedPaths will return every attributes updated
  const locked_props = [ Set([...this.locked_props, this.modifiedPaths()])];
  this.set({ locked_props  });

Hi, thanks for your reply!.

I think it was using hooks, but the problem is that is not working because i wanna use when i update a field and as its says on the documentation: *Pre and post ‘save()’ hooks are not executed on update(), findOneAndUpdate(), etc.
Is there any other posibility to achive the objective?

I was able to solve it with the following code:

  schema.pre("findOneAndUpdate", async function () {
    const modifiedFields = this.getUpdate().$set;
    key = Object.keys(modifiedFields);
    const docToUpdate = await this.model.findOne(this.getQuery());
    const locked_props = key;
    this.update({ $push: { locked_props: key } });


1 Like