Accessing the MongoDB database via Node.js
We are now going to create a new web server that, instead of returning users from a JSON file, returns the list of users from our previously created users
collection:
- In the
ch2
folder, open a Terminal. Install themongodb
package, which contains the official MongoDB driver for Node.js:$ npm install [email protected]
- Create a new
backend/mongodbweb.js
file and open it. Import the following:import { createServer } from 'node:http' import { MongoClient } from 'mongodb'
- Define the connection URL and database name and then create a new MongoDB client:
const url = 'mongodb://localhost:27017/' const dbName = 'ch2' const client = new MongoClient(url)
- Connect to the database and log a message after we are connected successfully, or when there is an error with the connection:
try { await client.connect() console.log('Successfully connected to database!') } catch (err...