Searching for user by email in AirTable database

I’m working on a project where I need to check if a user exists in my AirTable database by their email. If they don’t exist, I want to add them. Here’s what I’ve tried so far:

const AirTable = require('airtable');
const db = new AirTable({ apiKey: process.env.API_KEY }).base(process.env.BASE_ID);

app.post('/registerUser', (req, res) => {
  const { id, name, email, avatar, authType } = req.query;
  db('users').select({
    filterByFormula: `EMAIL = '${email}'`
  }).firstPage((err, records) => {
    if (err) {
      res.status(500).json({ error: err.message });
      return;
    }
    if (records.length === 0) {
      db('users').create([{ fields: { id, name, email, avatar, authType } }], (err, newRecords) => {
        if (err) {
          res.status(500).json({ error: err.message });
        } else {
          res.json(newRecords[0].fields);
        }
      });
    } else {
      res.json(records[0].fields);
    }
  });
});

But I’m getting a ‘NOT_FOUND’ error. I’ve also tried using find instead of select, but that didn’t work either. Any ideas on what I’m doing wrong or how to fix this?

I’ve encountered similar issues with AirTable before. The ‘NOT_FOUND’ error typically occurs when there’s a problem with the base ID or table name. Double-check that your BASE_ID environment variable is correct and that you’re using the right table name in db(‘users’).

Also, your current approach is vulnerable to SQL injection. Instead of string interpolation, consider using parameterized queries to ensure security. For example, you might change:

filterByFormula: `EMAIL = '${email}'`

to something safer that properly handles the email input. If this doesn’t resolve the error, try logging the full error object for more detailed debugging information.

I’ve dealt with similar AirTable issues in my projects. One thing that’s worked for me is using the ‘maxRecords’ parameter with select(). It can help optimize your query, especially if you’re only expecting one result:

db('users').select({
  filterByFormula: `EMAIL = '${email}'`,
  maxRecords: 1
}).firstPage((err, records) => {
  // Your existing code here
});

Also, make sure your ‘users’ table actually exists in your base. I once spent hours debugging only to realize I’d mistyped the table name. If you’re still getting errors, try wrapping your AirTable calls in a try-catch block for better error handling. It’s saved me countless times when dealing with API inconsistencies.

hey, try using findRecordByFields. it’s simpler than select. for ex:

db('users').findRecordByFields('EMAIL', email, (err, record) => { ... });

could help. gud luck!