Sithys
Sithys

Reputation: 3793

findOneAndUpdate in mongodb return only updated values

I have to create a logbook for my application (MEAN-Stack). I need to know, which user changed fields inside the customer document and when he did it. Knowing which user it was and when is no problem. But i want my logbook to be as "clean" as possible so i would like to only write down changed values.

Lets take this example:

customer : {
    name: Customer Ltd.
    address: FooStreet 11
    zip: 21412
    country: Germany
}

the user now changes the zip with this function (req.body.customer includes whole customer document, not only changed fields)

const customer = await Customer.findOneAndUpdate({ _id: req.body.id }, { $set: req.body.customer }, { new: true });

is there any possibility to get changed fields from findOneAndUpdate() or maybe there is a better approach to solve what i want?

Any help would be really appreciated!

Upvotes: 0

Views: 583

Answers (1)

klhr
klhr

Reputation: 3380

findOneAndUpdate takes a returnNewDocument option that returns the updated document rather than the original document -- https://docs.mongodb.com/manual/reference/method/db.collection.findOneAndUpdate/

Upvotes: 1

Related Questions