MongoDB with Node.js

Using MongoDB with Node.js is straightforward with the official mongodb driver. Its methods mirror mongosh almost exactly, but they return Promises, so you use async/await.

Install and Connect

Install the driver and keep your connection string in an environment variable, never in code. Create one MongoClient and reuse it for the whole app.

// npm install mongodb
import { MongoClient } from 'mongodb'

const client = new MongoClient(process.env.MONGODB_URI ?? 'mongodb://127.0.0.1:27017')
await client.connect()
const db = client.db('shop')
console.log('Connected to', db.databaseName)
Connected to shop

Insert and Find

find() returns a cursor; call toArray() to get an array.

const products = db.collection('products')

await products.insertOne({ name: 'Sea Salt', category: 'Spices', price: 2, stock: 400 })

const cheap = await products
  .find({ price: { $lt: 5 } }, { projection: { _id: 0, name: 1, price: 1 } })
  .sort({ price: 1 })
  .toArray()
console.log(cheap)
[ { name: 'Sea Salt', price: 2 }, { name: 'Dark Chocolate', price: 4.25 } ]

Update and Delete

const res = await products.updateOne({ name: 'Sea Salt' }, { $inc: { stock: -50 } })
console.log(res.modifiedCount)

const del = await products.deleteOne({ name: 'Sea Salt' })
console.log(del.deletedCount)
1
1

Working with ObjectId

IDs from URLs are strings; convert them with new ObjectId(id) before querying.

import { ObjectId } from 'mongodb'

const id = '6720a5e2c2b9e81d4f3a1b0a'
const honey = await products.findOne({ _id: new ObjectId(id) })
console.log(honey?.name)
await client.close()
Honey

Frequently asked questions

Should I open a new MongoDB connection per request?

No. Create one MongoClient when the app starts and reuse it; it manages a connection pool for you.

Mongoose or the native driver?

The native driver is lighter and gives full control. Mongoose adds schemas, validation and middleware, which many Express projects find convenient.

How do I fix "MongoServerSelectionError"?

The driver could not reach the server. Check that MongoDB is running, the URI is correct, and your IP is allowed in Atlas Network Access.