Everything so far ran directly in mongosh. Real applications talk to MongoDB from application code instead — this lesson connects a Node.js app to MongoDB using the official mongodb driver.
npm install mongodbimport { MongoClient } from "mongodb"
const uri = "mongodb+srv://<username>:<password>@cluster0.xxxxx.mongodb.net/"
const client = new MongoClient(uri)
async function main() {
await client.connect()
console.log("Connected to MongoDB")
}
main()Get a reference to a database and collection, then use the same method names you already know from mongosh — find(), insertOne(), updateOne(), and the rest all exist on the driver, as async functions:
const db = client.db("learningMongo")
const users = db.collection("users")
const allUsers = await users.find().toArray()
console.log(allUsers)In a short script, close the connection when done. In a long-running web server, you typically connect once at startup and keep the connection open for the app's lifetime instead:
await client.close()Never commit real credentials
Never hardcode a connection string containing a real username and password directly in a committed file. Store it in an environment variable instead — see this site's process & Environment Variables lesson.