Sobes.tech
Junior — Middle

How to add new records to a database?

sobes.tech AI

Answer from AI

To add new records to a database in Node.js, developers typically use drivers or ORMs, such as mysql, pg for SQL databases, or mongoose for MongoDB.

Example using mysql:

const mysql = require('mysql');
const connection = mysql.createConnection({
  host: 'localhost',
  user: 'user',
  password: 'password',
  database: 'testdb'
});

connection.connect();

const newUser = { name: 'Ivan', age: 30 };
connection.query('INSERT INTO users SET ?', newUser, (error, results) => {
  if (error) throw error;
  console.log('Record added with ID:', results.insertId);
});

connection.end();

If using an ORM like Sequelize, adding a record might look like this:

const User = require('./models/user');

async function addUser() {
  const user = await User.create({ name: 'Ivan', age: 30 });
  console.log('User added with ID:', user.id);
}

addUser();

The main thing is to prepare the data and execute the appropriate query or ORM method to insert the record.