Search code examples
javascriptmongodbfunctionecmascript-6serverless

Cannot update the nested Array of the boolean


I am trying to update an array to show the router is up by using a true or false statement.

But I am getting a response back that "record is updated" but I am not able to see the change in MongoDB collection.

This is my function I am running

exports = async function({ body }) {
  const data = JSON.parse(body.text());
  const ACAS_Mission = data.ACAS_Mission;
  const terminal = data.terminals[0].terminal;
  const router = data.terminals[0].XLESS.router;

  const comstat = context.services
    .get("mongodb-atlas")
    .db("Comstat")
    .collection("comstat");

  // Find the document
  const filter = { ACAS_Mission, "terminals.terminal": terminal };
  const document = await comstat.findOne(filter);
  console.log("Document:", JSON.stringify(document));

  // Update the document
  const updateFilter = { ACAS_Mission, "terminals.terminal": terminal };
  const update = { $set: { "terminals.$[t].XLESS.router": router } };
  const options = { arrayFilters: [{ "t.terminal": terminal }] };
  const result = await comstat.updateOne(updateFilter, update, options);
  console.log("Update result:", JSON.stringify(result));

  return { message: "Record updated." };
};

and this is the document I am trying to update

MongoDB Document

The JSON Body that I am passing when I do a PUT

{
  "ACAS_Mission": "xx53583",
  "terminals": [
    {
      "terminal": "SNN573330",
      "XLESS": {
        "router": true
      }
    }
  ]
}

Solution

  • As you wrote in your comment, MongoDB processes the request, but there are no changes. That means that nothing in your datebase matched your query (as one may conclude from matchedCount being 0).

    Check your query: Your screenshot shows that terminals contains an array containing another array containing an object. You are searching for an array directly containing an object, so adding [braces] around the statement might work.