Cannot accesd an index on Fauna local

I am running a local instance of Fauna which I access through a Netlify app. I have a collection (users) with an index (users_by_username) with one record which I can access through fauna shell using the secret used in my app

users.users_by_username("fred")

giving the result

{
  data: [
	{
	  id: "650044333971413209",
	  coll: users,
	  ts: Time("2024-01-02T12:31:20.100Z"),
	  first_name: "Fred",
	  last_name: "Dibnah",
	  login_id: "123621b8-d6fc-465e-90ae-dca8d83e3321x",
	  email: "jeff@xmail.com",
	  username: "fred",
	  contacts: []
	}
  ]
}

However when I attempt to access it through the app I get an error

when reading user: Ref refers to undefined index ‘users_by_username’

The code here is cut down to a minimum

db-access.js in …/netlify/functions

var fclient = new faunadb.Client(
    {
        secret: 'fnAFWr6 ....',
        domain: 'localhost',
        port: '8443',
        scheme: 'http',
    }
)

exports.handler = async () => {
    var query = faunadb.query
    try {
        var query_function = query.Map(
            query.Paginate(query.Match(query.Index('users_by_username'), 'fred')),
            (recordRef) => query.Get(recordRef)
        );
        var response = await fclient.query(query_function);

        return {
            statusCode: 200,
            body: JSON.stringify(response.data),
            headers: {
                "Access-Control-Allow-Origin": "*",
                "Access-Control-Allow-Credentials": true,
            },
        };
    } catch (error) {
        return {
            statusCode: 422,
            body: JSON.stringify(error),
        };
    };
};

Why can it not find the index?

This syntax is FQL v10 syntax:

users.users_by_username("fred")

But the query code you have written below is v4 syntax and I am assuming the v4 js driver.

If you created a v10 index then you should use the v10 driver to access it:

import { Client, fql } from 'fauna'

const client = new Client({
    secret,
    endpoint: new URL(`http://localhost:8443`)
  })

const targetUsername = "fred"

client.query(
fql`
  users.users_by_username(${targetUsername}).first()
`
)

Basically, you can’t directly access v4 indexes from v10 code, and you can’t directly access v10 indexes from v4 code either. You can indirectly access them by wrapping them in a UDF that does the index access and returns a page and then using that data from the other fql version if you need to.

1 Like

Thanks

I was asleep and wasn’t aware of the the migration to v10

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