Junior — Middle
What time management methods do you use for effective work?
sobes.tech AI
Answer from AI
To improve the efficiency of database queries in Node.js, you can use the following approaches:
- Indexing: create indexes on columns frequently used in search conditions to speed up lookups.
- Pagination and limiting: do not load all data at once, use
LIMITandOFFSETor cursors to fetch data in portions. - Query optimization: avoid operations that do not use indexes (e.g., functions on columns in WHERE), select only necessary fields.
- Caching: store results of frequent queries in cache (Redis, Memcached).
- Connection pooling: use a pool of connections to the database to reduce connection overhead.
- Parallel queries: if possible, execute independent queries in parallel.
- Use ORM wisely: monitor the generated queries, optimize or write raw SQL if needed.
- Profiling and monitoring: analyze slow queries and optimize them.
Example of using connection pool with mysql2:
const mysql = require('mysql2/promise');
const pool = mysql.createPool({
host: 'localhost',
user: 'root',
database: 'test',
waitForConnections: true,
connectionLimit: 10,
queueLimit: 0
});
async function getUsers(limit) {
const [rows] = await pool.query('SELECT id, name FROM users LIMIT ?', [limit]);
return rows;
}
This approach reduces connection wait time and improves overall performance.