Choose the best reason why connecting to a database is crucial for most Node.js apps.
Think about what apps do with user information or content they show.
Database connectivity lets apps save and get data like user info or posts. Without it, apps can't remember or change data.
Consider a Node.js app that tries to fetch user data but the database connection fails. What will likely happen?
Think about what happens when the app asks for data but none arrives.
If the app can't connect to the database, it can't get data and usually throws an error or stops working properly.
Which code snippet correctly connects to a MongoDB database using the mongodb package?
const { MongoClient } = require('mongodb');
const uri = 'mongodb://localhost:27017';
async function connect() {
// connection code here
}Remember to create a new MongoClient with the URI and use await to connect.
Option B correctly creates a new MongoClient with the URI and uses await client.connect() to establish the connection.
Consider this code snippet using pg package for PostgreSQL:
const { Client } = require('pg');
const client = new Client({ connectionString: 'postgresql://user:pass@localhost/db' });
async function run() {
await client.connect();
const res = await client.query('SELECT 1 AS number');
console.log(res.rows[0].number);
await client.end();
}
run();What will be printed to the console?
The query selects a constant number 1 as 'number'.
The query returns one row with a column 'number' equal to 1, so res.rows[0].number is 1.
Examine the code below:
const { Client } = require('pg');
const client = Client({ connectionString: 'postgresql://user:pass@localhost/db' });
async function run() {
await client.connect();
const res = await client.query('SELECT NOW()');
console.log(res.rows[0]);
await client.end();
}
run();Why does it throw the error?
Check how the Client object is created.
The Client constructor must be called with new. Without it, client is not an instance and lacks query.