Check uniqueness

A simple usecase — be sure that documents are unique, indexed by a given field.

Intuitively, I try this:

const query = fql`
    let theUser = User.by_name(${userData.username}).first()
    
    if (theUser.exists()) {
        abort("Username exists already.")
    } else {
        User.create({
            username: ${userData.username},
            password: ${hashValue}
        })
    }
`

But I get an error response,

error: Type Null is not a subtype of Boolean

That is exactly what I want to check for — null or does it exist.

I have tried searching across the docs and forums; a problem is that search queries return results from the previous version of Fauna query language.

I believe this link explains your issue:

Basically, you could use either of these

let alreadyExists = theUser != null

or

let isUnique = User.by_name(${userData.username}).isEmpty()
1 Like

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