Watch keynotes and sessions from MongoDB.live, our virtual developer conference.

Comparing strings to ObjectIds in Rules

I’m having trouble creating a document rule for matching the %%user.id (which I believe is a string) to an ObjectId field (_id).

The scenario is documents that have _ids which are ObjectId conversions of the authenticated user_id.

Here is the rule that does not work:

{
  "_id": "%%user.id"
}

However, if I make an id field that is a string of the same value and adjust the rule from _id to id, it works.

Should I just make my document _id’s strings, or is there a way to compare an ObjectId to a string in a rule?

My solution is to make a string id field that equals the _id so I can compare it to %%user.

{
  "id": "%%user.id"
}

It would be nice if I could do something like

{
  "_id": "ObjectId(%%user.id)"
}

but this will work for now.

@Matt_Jennings Yes you can either use a string as an Id or use a function to perform the conversion and compare for you -

https://docs.mongodb.com/realm/functions/call-a-function/index.html#call-from-a-json-expression