Can't set Triggers in Atlas

Hello guys, Please help.
I am trying to set a trigger in my Atlas, unfortunately, I cannot set the trigger.
I get this error:

> error: 
{"message":"Cannot access member 'db' of undefined","name":"TypeError"}

Here’s my function code:

exports = async function() {
  const mongodb = context.services.get("mongodb-atlas");
  const salonsCollection = mongodb.db("clippersDB").collection("salons");

  try {
    await salonsCollection.updateMany({}, [
      {
        $inc: {
          waitTime: -1,
          "barbers.$[].workingTime": -1
        }
      }
    ]);

    console.log("Update operation completed successfully.");
  } catch (error) {
    console.error("Error occurred during update operation:", error);
  }
};

Although I created an app in Realm and set up a trigger there and it is working with the following code:

exports = async function() {
  const mongodb = context.services.get("mongodb-atlas");
  const client = mongodb.db("clippersDB").getClient();
  const collection = client.db("clippersDB").collection("salons");

  // Fetch all salons
  const salons = await collection.find({}).toArray();

  // Update workingTime of barbers and waitTime of salons
  const updatedSalons = salons.map(salon => {
    const updatedBarbers = salon.barbers.map(barber => {
      const updatedWorkingTime = barber.workingTime > 0 ? barber.workingTime - 1 : 0;
      return { ...barber, workingTime: updatedWorkingTime };
    });
    const updatedWaitTime = salon.waitTime > 0 ? salon.waitTime - 1 : 0;
    return { ...salon, barbers: updatedBarbers, waitTime: updatedWaitTime };
  });

  // Update the salons in the database
  await Promise.all(updatedSalons.map(updatedSalon => collection.updateOne({ _id: updatedSalon._id }, updatedSalon)));

  console.log("WorkingTime and WaitTime updated successfully.");
};

Then why am I getting errors accessing the db database which exists?

The error seems to indicate that this is failing:

  const mongodb = context.services.get("mongodb-atlas");

I.e. the call to the context could not find a database link called “mongodb-atlas”.

Are you sure the name is correct? Is the trigger within an Atlas application, if so you can check in the “Linked Data Sources” from the left have navigation area to view what’s configured and their name?

In the above case, I’d use my-app-connection as the string to lookup from the line above.

1 Like

Thanks a lot!
I thought all services were “mongodb-atlas”. Fixed.

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.