Home > Blockchain >  How can I check whether a document exists based on an optional field?
How can I check whether a document exists based on an optional field?

Time:09-04

I am writing some Firestore rules to allow users to create posts and reply to each other. I have some rules to check whether a post is valid.

function isPost(data) {
  return data.keys().hasOnly(["title", "text", "parent")
    && data.title is string
    && data.get("text", "") is string
}

How can I add an optional "replyTo" field that would only be valid if it references an existing document (post) in the db?

I've tried this


function isPost(data) {
  return data.keys().hasOnly(["title", "text"])
    && data.title is string
    && data.get("text", "") is string
    && exists(/databases/$(database)/documents/posts/$(data.get("replyTo", "")))
}

but it doesn't return a reference to a valid document, and therefore fails.

EDIT: Working solution based on @Dharmaraj's answer:

function isPost(data) {
  return data.keys().hasOnly(["title", "text"])
    && data.title is string
    && data.get("text", "") is string
    && !('replyTo' in data) || exists(/databases/$(database)/documents/$(data.replyTo))

}

CodePudding user response:

If the replyTo field is a reference then it's value would be posts/postId so you don't need collection name in path:

// remove /posts from this
exists(/databases/$(database)/documents/$(data.replyTo))

The following rule will pass if replyTo field is missing or will ensure the document referenced exists in case it does:

allow read: if !('replyTo' in data) || exists(/databases/$(database)/documents/$(data.replyTo))
  • Related