node.jsrestcassandradatastax-astrastargate-oss

Issue inserting a new record with @astrajs/rest


I'm new to astra db, and am having issues trying to insert a record into my table called 'usersnew' when using @astrajs/rest

This is the structure of my table:

CREATE TABLE mykeyspace.usersnew (
    id uuid PRIMARY KEY,
    email text,
    name text,
    userhandle text
)

1/ If I create a user and create/populate the ID field (the uuid), it works PERFECTLY!

    // create a new user with a document id -- seems to work!
      const { data, status } = await astraClient.put(
          "/api/rest/v2/keyspaces/mykeyspace/usersnew/ddd795a9-a9a2-49ca-a6a7-a29e1b039e20",
          {
            email: "abc@abc",
            name: "cliff",
            userhandle: "handlethis"
          }
        );

2/ If I try to create a user without specifying the ID field, it SADLY FAILS

    // creating a user without passing in a ID field
     const { data, status } = await astraClient.post(
          "/api/rest/v2/keyspaces/mykeyspace/usersnew", 
          {
            email: "aaa@aaa",
            name: "aaaa",
            userhandle: "handlethat"
           }
        );

This is the error I'm getting:

Astra Client Error: Error: Request Failed: [object Object]
Stack Trace: Request failed with status code 404

If someone could kindly help me that would be hugely appreciated. I've been trying to solve this for a whole day now with no luck at all.

I have been following the datastax documentation as well on this, but it's often wrong / inconsistent, sadly.

https://docs.datastax.com/en/astra-serverless/docs/develop/dev-with-rest.html


Solution

  • Your code is failing because you have not specified the ID. It is not possible to perform CRUD operations on Cassandra without specifying the partition key.

    In Cassandra, the partition key is used to partition the data meaning that the partition key is used to determine which node(s) the data partition (record) gets stored.

    In your case, id is the partition key. You have to specify an id or Cassandra doesn't know which partition the data belongs to.

    As a side note, it is not necessary to use "artificial" keys like a UUID. We recommend using "natural" keys like email addresses as the partition key since they are universally unique. Similarly, you can use userhandle as the partition key if they are unique across the whole domain.

    Here are some examples for partitioning with natural keys instead of artificial IDs:

    CREATE TABLE users_by_email (
        email text,
        name text,
        userhandle text,
        PRIMARY KEY (email)
    )
    
    CREATE TABLE users_by_handle (
        userhandle text,
        email text,
        name text,
        PRIMARY KEY (userhandle)
    )