Search code examples
faunadb

How to get the ref(id) of my last instance created


I don't know how to simply get the ref(id) of my last instance created with faunadb. I need to put it in an url.

I use this to create my instance:

/* code from functions/todos-create.js */
import faunadb from 'faunadb' /* Import faunaDB sdk */
/* configure faunaDB Client with our secret */
const q = faunadb.query
const client = new faunadb.Client({
  secret: process.env.FAUNADB_SECRET
})

/* export our lambda function as named "handler" export */
exports.handler = (event, context, callback) => {
  /* parse the string body into a useable JS object */


  const eventBody = JSON.stringify(event.body)
  const data = JSON.parse(eventBody)
  const mission = {
    data: JSON.parse(data)
  }
  // {"title":"What I had for breakfast ..","completed":true}
  /* construct the fauna query */
  return client.query(q.Create(q.Ref("classes/missions"), mission))
  .then((response) => {
    console.log("success", response)
    /* Success! return the response with statusCode 200 */
    return callback(null, {
      statusCode: 200,
      body: JSON.stringify(response)
    })
  }).catch((error) => {
    console.log("error", error)
    /* Error! return the error with statusCode 400 */
    return callback(null, {
      statusCode: 400,
      body: JSON.stringify(error)
    })
  })
}

I begin to dev, and I need to do this simply with faunadb, can you help me please ?


Solution

  • Instance creation returns a ref, as along with other instance metadata and the user supplied instance data. This means we can compose a select with the create to pull the data out that you require. Using the shell syntax:

    Select("ref", Create(Class("missions"), {...})
    

    will yield the ref. Of course if you'd like just the id part of the ref you can drill in further:

    Select(["ref", "id"], Create(Class("missions"), {...})