Atlas Function findOne with multiple queries

I’m using the findOne function on a MongoDB Atlas Function … I’m trying to match multiple data points but it doesn’t seem to match on these. I definitely have a document in my collection that matches however it always returns ``null`.

const matcher = await myCollection.findOne({
    object_id: `${event.fullDocument.object_id}`,
    user_id: `${event.fullDocument.user_id}`,
    expiry: { $gt: new Date() }
  });

Is there anything I’m doing wrong here? How can I get data back that matches these 3?

Thanks

Are you sure all those ids are strings? Can you paste in a document you think should match?

and the values of event.fullDocument fields you are using.

The reason John asked you

is because the syntax you used in

that is, the back tick and ${}, aka template literals will generate string values for your query. So if object_id and user_id in your documents are anything other than strings the query will not work event if event.fullDocument.object_id and event.fullDocument.user_id are not strings.

Exactly, thanks Steevej for elaborating on my reply, it could have been a touch more in-depth but this is exactly the point, you could be comparing ObjectIDs to strings which will not match and result in no results. Something else to try when debugging is to put the filter you’re creating in a variable and log that to the console. You can then take what it being run and try it out in a script window to investigate further.

So something like this:

const myFilter = {
    object_id: `${event.fullDocument.object_id}`,
    user_id: `${event.fullDocument.user_id}`,
    expiry: { $gt: new Date() }
}

console.log(JSON.stringify(myFilter));

const matcher = await myCollection.findOne(myFilter );

(Obviously be careful about leaving this in when you’re done!)

2 Likes

@Ben_Read, please followup on your thread.

It has been more than a week since you got pertinent replies. If one is the solution please mark it as such to provide closure.

If you find a solution not mentioned in your replies please share it and mark it as the solution.

Thanks in advance

Hi both,
Sorry for the late reply, and thank you for your help. Yes those were definitely both strings, but I have been having issues relating to date objects in MongoDB, and I think that was causing the error.

1 Like