Search code examples
javascriptreactjsnext.jsfaunadb

Updating a value via a FaunaDB query


I have a ReactJS NextJS web-app. The following code outputs the correct values to the terminal however it fails to update the database at all. As such, I think that the faunaDB Update function is incorrectly specified. All 4 console.log calls are outputting the correct values.

const faunadb = require("faunadb");

// your secret hash
const secret = process.env.FAUNADB_SECRET_KEY;
const q = faunadb.query;
const client = new faunadb.Client({ secret });

console.log("CALLLED API")

module.exports = async (req, res) => {
  const formData = req.body;
  console.log("API CALL");
  try {
    const dbs = await client.query(
      console.log("API UPDATE"),
      console.log(formData.likes[0].data.like + 1),

      q.Update(
        q.Ref(q.Collection('Likes'), '__likes_reference__'),
        {
          data: {
            like: formData.likes[0].data.like + 1,
          },
        }
      )
    );
    // ok
    res.status(200).json(dbs.data);
  } catch (e) {
    // something went wrong
    res.status(500).json({ error: e.message });
  }
};

How can I increment the value for likes in the database?


Solution

  • I increment the value for likes by 1 with the following code:

    q.Update(
                q.Ref(q.Collection('Likes'), '__likes_reference__'),
                    {
                        data: {
                            like: q.Add(
                                q.Select(
                                    ['data', 'like'],
                                    q.Get(
                                        q.Ref(
                                            q.Collection('Likes'),
                                            '__likes_reference__'
                                        )
                                    )
                                ),
                                1
                            )
                        }
                    },
                )