Connecting from Node and Saving Documents
The official mongodb package connects Node to MongoDB with a MongoClient made from a connection string kept in .env, saves documents with insertOne and insertMany, reads them back with find().toArray(), and closes the client when the work is done.
Apprentice · MongoDB · Node.js · Updated
After this lesson you can
- Connect to MongoDB from Node with MongoClient, using a connection string from .env, and close the client when the work is done
- Save documents with insertOne and insertMany, and read the ids they give back
- Read the documents in a collection with find().toArray(), every one or only those whose field has a given value
Key takeaways
- npm install mongodb adds the official driver. new MongoClient(uri) makes a client, client.db() picks a database and db.collection() a collection.
- Keep the connection string in a .env file, list .env in .gitignore, and run the script with node --env-file=.env.
- insertOne saves one document and gives back its insertedId. insertMany saves a list and gives back insertedCount and insertedIds.
- find().toArray() gives back every document in a collection as an array of objects. Given a field and a value, such as petSafe and true, find gives back only the documents that match.
- Close the client with client.close() when the script is done. MongoServerSelectionError with ECONNREFUSED means no MongoDB answered at that address.
Every API in the rest of this course saves and reads its data the way this lesson does. The code is short, and the same few lines (make a client, pick a collection, insert, find, close) sit underneath sign-ups, orders and every list a front end shows.
Fern & Fig's plants are still in a JSON file. Time to move them into the MongoDB you set up in Setup: MongoDB and Compass.
A project, a driver and a .env file
Node can't talk to MongoDB by itself. It needs a driver: a package that knows how to send MongoDB your requests and read its answers. MongoDB makes the official one, the mongodb package. Make a folder named plant-shop, give it a package.json holding { "type": "module" }, and install the driver in VS Code's terminal:
npm install mongodb
The connection string goes in a file named .env beside your code, as Settings from Environment Variables showed. Today it's your own computer; later it could be an Atlas string with a password, so it never goes in the code. Put .env in a .gitignore file too, so Git leaves it out. The .env file holds one line:
MONGODB_URI=mongodb://localhost:27017
Connecting: a client, a database and a collection
A MongoClient is your program's line to the server, made from the connection string. From the client you pick a database, and from the database a collection, by name. Neither has to exist yet: MongoDB makes both the first time you save a document in them. Make insert-one.js:
import { MongoClient } from "mongodb";
const client = new MongoClient(process.env.MONGODB_URI);
const db = client.db("plant_shop");
const plants = db.collection("plants");
const result = await plants.insertOne({
name: "Snake Plant",
price: 24,
petSafe: false,
care: { light: "low to bright, indirect", water: "every 2 to 3 weeks" },
});
console.log(result.insertedId);
await client.close();
Run it with the .env file loaded:
node --env-file=.env insert-one.js
new ObjectId('6afc92c27e448083e9c96f30')
The client connects by itself the first time you use it. insertOne saves one document and gives back a result whose insertedId is the _id the new document got, a fresh ObjectId (yours will be different). Each call is awaited, because the answer comes back from another program. And client.close() at the end hangs up, so the script can finish: without it, Node keeps the line open and the script never ends.
Saving several: insertMany
insertMany saves a whole list in one trip to the server. Make seed.js, which fills the catalog. It starts by emptying the collection with deleteMany({}), so you can run it again without doubling every plant (Updating and Deleting Documents covers deleting):
import { MongoClient } from "mongodb";
const client = new MongoClient(process.env.MONGODB_URI);
const plants = client.db("plant_shop").collection("plants");
await plants.deleteMany({});
const result = await plants.insertMany([
{ name: "Snake Plant", price: 24, petSafe: false },
{ name: "Spider Plant", price: 14, petSafe: true },
{ name: "Boston Fern", price: 22, petSafe: true },
]);
console.log(result.insertedCount);
console.log(result.insertedIds);
await client.close();
3
{
'0': new ObjectId('6afc92c2e5a5f45e301e569f'),
'1': new ObjectId('6afc92c2e5a5f45e301e56a0'),
'2': new ObjectId('6afc92c2e5a5f45e301e56a1')
}
insertedCount is how many were saved. insertedIds holds each new _id by its position in your list: '0' is the Snake Plant's.
Reading them back: find().toArray()
find() asks for the documents in a collection, and toArray() collects every one into an ordinary array. Give find a document of fields and values, such as { petSafe: true }, and you get only the documents whose fields match; Finding Documents with Filters goes much further. Make read.js:
import { MongoClient } from "mongodb";
const client = new MongoClient(process.env.MONGODB_URI);
const plants = client.db("plant_shop").collection("plants");
const all = await plants.find().toArray();
console.log(all.length);
console.log(all[1]);
const petSafe = await plants.find({ petSafe: true }).toArray();
console.log(petSafe.map((plant) => plant.name));
await client.close();
3
{
_id: new ObjectId('6afc92c2e5a5f45e301e56a0'),
name: 'Spider Plant',
price: 14,
petSafe: true
}
[ 'Spider Plant', 'Boston Fern' ]
Each document comes back as a plain object, _id included. Now open Compass, click Refresh if the list was already open, and the plant_shop database shows its plants collection with the three plants inside.
When it can't connect
If the server isn't running, or the connection string has a typo, nothing answers. The driver keeps trying for 30 seconds, then stops. To see it safely, change the port in .env to 27018, where nothing listens, and run read.js again. After half a minute, the most important line of what Node prints is:
MongoServerSelectionError: connect ECONNREFUSED ::1:27018, connect ECONNREFUSED 127.0.0.1:27018
ECONNREFUSED (read "E-CONN-REFUSED", connection refused) means nothing answered at that address. ::1 and 127.0.0.1 are two ways of writing localhost, and the driver tried both. Check that the server is running (Get-Service MongoDB, or brew services list), and check the port and spelling in .env. Put the port back to 27017 when you're done.
Check yourself
2 questions to try on the lesson page.
So what
Connect, pick a collection, insert, find, close: every route in your APIs that saves or lists something will be these same few lines, wrapped in a request handler.