.find( ) returning an empty object when called from a trigger

I’m creating a trigger for new entries in my comment collection. When a user leaves a comment, I want mongo to create a new entry in my notification collection with the comment and the post data. To get the data from the post collection, I’m executing post.find( ) but I’m getting an empty object. What am I doing wrong?

exports = async function(commentEvent) {
  const mongodb = context.services.get("fp-review");
  const userNotifications = mongodb.db("Notifications").collection("userNotifications");
  const posts = mongodb.db("fightpandemics").collection("posts");
  const { fullDocument } = commentEvent;
  
  const specificPost = await posts.find({_id: fullDocument.postId});

  const newEmailNotification = {
comment: fullDocument,
specificPost,
  };
  
  await userNotifications.insertOne(newEmailNotification);
}

Hi @Vinicius_Rodrigues,

I have an assumption that the postId in the received change document is a string while the _id is of type ObjectId.

I think you have to convert it to object Id:
https://docs.mongodb.com/realm/mongodb/find-documents/#query-based-on-a-document-s-id

const specificPost = await posts.find({_id: BSON.ObjectId(fullDocument.postId) });

Let me know if that helps

Best
Pavel

@Pavel_Duchovny when I convert it to BSON, I get this error:

Error:
{“message”:“ObjectId in must be a single string of 12 bytes or a string of 24 hex characters”,“name”:“Error”}

I tried executing the .find without any parameter but I’m still getting an empty object.
const specificPost = await posts.find();
It works fine when I execute separate as a mongodb realm function but when I call the function from the trigger I get an empty object. This is what I get when I console.log specificPost in both case above:
Logs:
[
“[object Object]”
]

I’m wondering if this issue has anything to do with permissions or access to the databases.

Hi @Vinicius_Rodrigues,

Can you send me a link to your realm app?

Also please try to print the following:

const specificPost = await posts.find({}).toArray();
console.log(JSON.stringify(specificPost));

Best
Pavel

It’s working now that I included .toArray() at the end of the function. Thanks a lot @Pavel_Duchovny

1 Like

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