Skip to content
Advertisement

How do I use $addToSet with objects in mongodb?

I want to push only unique objects into an array with $addToSet.

My userSchema has a field bankDetails which should take an array of objects:

JavaScript

I am updating the schema using the following controller function:

JavaScript

The data is saving correctly but Mongo auto generates an _id field every time so technically none of the objects are unique and the objects are repeatedly added.

Is anyone aware of a workaround for this?

Advertisement

Answer

You could check if a bank already exists, and add it only if not present:

JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement