Records: CRUD Operations

This script shows how to do basic CRUD (Create, Read, Update, Delete) operations on records in a NocoDB table. The script does these steps:

  1. It creates a table if the table does not exist.
  2. It adds fields.
  3. It creates demo records.
  4. It updates those records.
  5. It deletes the records.

For more information about the NocoDB API, refer to the NocoDB data API documentation.

const tableName = 'Contacts';
const fields = [
  { name: 'Name', type: 'SingleLineText' },
  { name: 'Email', type: 'Email' },
  {
    name: 'Status',
    type: 'SingleSelect',
    options: {
      choices: [
        { title: 'Active' },
        { title: 'Pending' },
        { title: 'Inactive' }
      ]
    }
  }
];

// Step 1: Create table if it doesn’t exist
let table = base.getTable(tableName);
if (!table) {
  table = await base.createTableAsync(tableName, []);
}

// Step 2: Create any missing fields
const existingFieldNames = table.fields.map(f => f.name);
for (let field of fields) {
  if (!existingFieldNames.includes(field.name)) {
    await table.createFieldAsync({ name: field.name, type: field.type, options: field.options });
  }
}

// Step 3: Create demo records
const recordsToCreate = [
  { fields: {
    'Name': 'John Doe',
    'Email': 'john.doe@example.com',
    'Status': 'Active'
  }},
  { fields: {
    'Name': 'Jane Smith',
    'Email': 'jane.smith@example.com',
    'Status': 'Pending'
  }},
  { fields: {
    'Name': 'Bob Johnson',
    'Email': 'bob.johnson@example.com',
    'Status': 'Active'
  }}
];

const createdRecords = await table.createRecordsAsync(recordsToCreate);
output.text(`βœ… Created ${createdRecords.length} new records.`);

// Step 4: Read the created records
const records = await table.selectRecordsAsync();
const created = records.records.filter(r => createdRecords.includes(r.id));

const displayBeforeUpdate = created.map(r => ({
  Name: r.getCellValue('Name'),
  Email: r.getCellValue('Email'),
  Status: r.getCellValue('Status')
}));

output.text('πŸ“– Records after creation:');
output.table(displayBeforeUpdate);

// Step 5: Update status of each record to "Inactive"
const updates = created.map(r => ({
  id: r.id,
  fields: {
    Status: 'Inactive'
  }
}));

await table.updateRecordsAsync(updates);

const updated = await table.selectRecordsAsync();
const updatedDisplay = updated.records.filter(r => createdRecords.includes(r.id)).map(r => ({
  Name: r.getCellValue('Name'),
  Email: r.getCellValue('Email'),
  Status: r.getCellValue('Status')
}));

output.text('πŸ” Records after status update:');
output.table(updatedDisplay);

// Step 6: Delete the created records
await table.deleteRecordsAsync(createdRecords);
output.text(`πŸ—‘οΈ Deleted ${createdRecords.length} records.`);

Last updated on

Latest product updates?See Changelog
Stay in the loop? Follow us onLinkedInLinkedInYouTubeYouTubeXX