skip to Main Content

I have a trigger on new documents in collection A, in which I want to get a related record from the users collections.

I (think) I followed the documentation to the "t", but both the collection itself comes out empty and the actual user I’m trying to fetch. And ideas what I’m doing wrong?

exports = async function trigger(changeEvent) {
  const toolRecord = changeEvent.fullDocument;
  const usersCollection = await context.services
    .get("Cluster0")
    .db("mind-tools")
    .collection("users");

  const user = await usersCollection.find({ _id: toolRecord.userId });
  const users = await usersCollection.find({});

  const text = [
    "New tool record - " + toolRecord._id,
    toolRecord.toolKey,
    "users",
    JSON.stringify(usersCollection),
    JSON.stringify(users[0]),
    "user",
    toolRecord.userId,
    JSON.stringify(user),
    user.name,
    user.email,
  ]
    .filter(Boolean)
    .join("n");
}

2

Answers


    • Is it possible to console.log() different variables in your script to see what value they got in run time?
    • Also in the example provided in Atlas tutorial, the first line is
    exports = async function (changeEvent) { ...
    

    Without the keyword "trigger"

    Login or Signup to reply.
  1. Try to use findOne instead of find for the user.

    Replace:

    const user = await usersCollection.find({ _id: toolRecord.userId });
    

    with:

    const user = await usersCollection.findOne({ _id: toolRecord.userId });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search