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.
>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);