Search code examples
javascriptnode.jsmongodb

How does $addToSet work if field is null?


Consider the 2 following Mongo Document structures:

{"SerialNumber": String, "IDs": ['x', 'y']}
{"SerialNumber": String, "IDs": null}

If the document looks like the first example, I'm able to use the following to add a new ID (where newID is a string) to the array.

await Device.updateOne({"SerialNumber": serialNumber}, {"$addToSet": {"IDs": newID }}).exec();

If the document looks like the second example, the update fails. Is there an existing method to update if the field is an array, like a nullable insert? Otherwise I'm thinking I would implement this logic:

    if(IDs === null) {
                            await IGmDevice.updateOne({"SerialNumber": serialNumber}, {"IDs": [newID] }).exec();
   } else {
                            await IGmDevice.updateOne({"SerialNumber": serialNumber}, {"$addToSet": {"IDs": newID}}).exec();
   }

I'm still testing, so not sure if this will work, but is there a better way to accomplish this?


Solution

  • You can use an update with an aggregation pipeline (array argument to update) and ifNull operator to replace null with an empty array prior to $addToSet.