2

I am trying to create a person record with the following code:

import Surreal from 'surrealdb.js';
...
const peopleFromSomewhere = await someProvider.getAllPeople();

// [{ email: 'some@email.com', fullName: 'Some Name' }, ... ]

for (const person of peopleFromSomewhere) {
  const created = await db.create('person', {
    email: person.email,
    fullName: person.fullName
  });
})

This creates a record with a randomly generated unique identifier, such as:

{ 
  email: 'some@email.com',
  fullName: 'Some Name',
  id: 'person:b5pfovinz7zkxlz3s8er'
}

But if I run the same code again, the same data will be inserted, just with a different UID.

I would like to use the email as a 'primary key' (using relational database terms) - to avoid inserting the same person twice, with the exact same details (email address & full name). How can I do this?

  const created = await db.create(`person:${person.email}`, {
    email: person.email,
    fullName: person.fullName
  });

Only gives me:

{ 
  email: 'some@email.com',
  fullName: 'Some Name',
  id: '⟨`person:some@email.com`⟩:w9m4l31bwti4472tdoax'
}

Which doesn't look quite right to me.

I expected:

{ 
  email: 'some@email.com',
  fullName: 'Some Name',
  id: 'person:'some@email.com''
}

How can I create a person record with the unique ID of an email address, so that I don't insert the same data twice?

nopassport1
  • 1,821
  • 1
  • 25
  • 53

1 Answers1

1

To create Record IDs with complex characters (such as the @ symbol) you have to surround the ID either with the ` or the and characters.

A query to create a record with such an ID would look like this:

CREATE user:⟨some@mail.com⟩ SET
  email = 'some@mail.com',
  fullName = 'Some Name'
;

Which would translate to the following query with the node.js driver:

let created = await db.create(`person:⟨${person.email}⟩`, {
  email: person.email,
  fullName: person.fullName
})

The record returned by the database then always includes the and , even if you surrounded the ID with the ` character.

[
    {
        "time": "73µs",
        "status": "OK",
        "result": [
            {
                "email": "some@mail.com",
                "fullName": "some name",
                "id": "person:⟨some@mail.com⟩"
            }
        ]
    }
]
Tobias S.
  • 21,159
  • 4
  • 27
  • 45
  • Thanks for the reply. May be a dumb question but how can I type out this symbol? It's neither `<`, `(` or `{` – nopassport1 Dec 26 '22 at 20:12
  • @nopassport1 - seems like there is no button on a standard keyboard to type those characters. I tried googling for shortcuts to write them but nothing worked for me. I would stick with the backtick for now personally. – Tobias S. Dec 27 '22 at 00:45
  • Okay, fair enough. Since we are unable to type out this character, please can you update your answer to include the following code? `await db.create(\`person:\\`${ person.email }\\`\`, {` – nopassport1 Dec 28 '22 at 12:13