Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Using multiple addToSet does not work for multiple arrays in one operation

I have a document with the following fields:

    ...
    firebaseTokens: { type: Map, of: String },
    androidIds: [{ type: String, maxlength: 128 }],
    advertisingIds: [{ type: String, maxlength: 128 }],
    firebaseInstallationIds: [{ type: String, maxlength: 128 }],
    ...

When I want to set all three arrays using $AddToSet at the same time in one operation, only the last array is set.

 let user = {
     _id: userId,
     $set: { [`firebaseTokens.${deviceId}`]: token, },
     $addToSet: { androidIds: deviceId },
     $addToSet: { advertisingIds: advertisingId },
     $addToSet: { firebaseInstallationIds: firebaseInstallationId }
 }
 let options = { new: true, setDefaultsOnInsert: true };
 let userDoc = await UserModel.findByIdAndUpdate(user._id, user, options);

In the above code, only firebaseInstallationIds are set.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The issue you’re encountering is due to the way the $addToSet operations are structured in your update object. In JavaScript, when you define an object with multiple properties having the same key, the last property overwrites all previous ones with the same key. This is why only firebaseInstallationIds is being set; it’s the last $addToSet operation in your object.

To fix this, you need to combine all $addToSet operations into a single object.

Here is the working example:

let user = {
    _id: userId,
    $set: { [`firebaseTokens.${deviceId}`]: token },
    $addToSet: {
        androidIds: deviceId,
        advertisingIds: advertisingId,
        firebaseInstallationIds: firebaseInstallationId
    }
}
let options = { new: true, setDefaultsOnInsert: true };
let userDoc = await UserModel.findByIdAndUpdate(user._id, user, options);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading