$ifNull not working as expected any help

I’ve recently made the switch from a self-hosted to a M0 cloud-hosted server, try before you buy to see if it is worth it for me kinda thing, and while doing some tests I have a problem with $ifNull.

simplified code

  const passwordHash = password == "" ? null : await bcrypt.hash(password, 10);
  let result = await accounts.updateOne(
    { _id: ObjectId(accountID) }, [{
    $set: {
      username: "name",
      passwordHash: { $ifNull: [passwordHash, "$passwordHash"] } }
  } ] );

but each time I try and update the account the passwordHash never changes, all the other fields do but not the passwordHash.

I have been trying to debug this for a few hours now and all the documentation I read is telling me it should work. I don’t remember this being a problem when I was self-hosting the server.

I don’t get any errors returned.
Is there anything I should do/check?

Hi :wave: @William_Brown,

Welcome to the MongoDB Community forums :sparkles:

Based on your code, it seems like you’re trying to update a document using the $ifNull operator to set the passwordHash field if it is null or missing in the document.

The syntax appears to be slightly incorrect. To ensure accuracy, please refer to the documentation for $ifNull. The correct format requires the field name to be listed first with a $ symbol, followed by the value you wish to use for updating. Here is the query snippet for reference:

         $project: {
            item: 1,
            description: { $ifNull: [ "$description", "Unspecified" ] }

Here example uses $ifNull to return the description if it is non-null and set it to "Unspecified" string if description is null or missing.

Meanwhile also note that, in MongoDB 4.4 and earlier versions, $ifNull only accepts a single input expression. Now in MongoDB 5.0 onwards it accepts multiple input expressions.

I hope it helps!


1 Like