- Install Node
- Install MongoDB Driver locally or create a MongoDB Atlas account (see below)
- Optional : install Compass
$ mkdir project && cd project
$ npm init -y
$ npm i mongodbCreate a database ("blog") and a collection ("posts"). Here a simple example in local with mongosh commands.
$ mongosh "mongodb://localhost:27017"
$ use blog
$ db.posts.insertOne( { "title":"First title (local)", "content":"First content" } );
$ show dbs
$ db.posts.find()import { MongoClient } from 'mongodb';
// const uri = process.env.STRING_URI; // MongoDB Atlas access
const uri = 'mongodb://localhost:27017';
const client = new MongoClient(uri);
async function runDB() {
try {
await client.connect();
// Establish and verify connection
await client.db('blog').command({ ping: 1 });
console.log('Connected successfully to the database');
// List posts
const posts = await client.db('blog').collection('posts').find().toArray();
console.log('POSTS : ', posts);
} catch (err) {
console.log(err);
} finally {
// Ensures that the client will close when you finish/error
await client.close();
}
}
runDB().catch(console.error);const databasesList = await client.db().admin().listDatabases();
console.log('DATABASES');
databasesList.databases.forEach((db) => console.log(`- ${db.name}`));const collections = await client.db('blog').listCollections().toArray();
console.log('COLLECTIONS : ', collections);const newPost = {
title: 'Title from node',
content: 'Lorem Ipsum',
};
const results = await client.db('blog').collection('posts').insertOne(newPost);
console.log(`The new post is created, see the new Id : ${results.insertedId}`);const results = await client.db('blog').collection('posts').insertOne(req.body);
res.status(201).send(results);See more on this updated tutorial
- Create an account
- Choose a cluster, you can rename it
- Security Quickstart > Authentification with a name and a password
- Security > Network Access > Add IP addresses
- Database > Collections > Add a database "blog" and a collection "posts"
- Database > Connect : copy the link mongodb+srv (string URI)
- DataBase > Connect > Your Application : copy the link to use it with node
- Optional : try with Compass
Protect your connexion string (username and password) with dotenv package
- Install dotenv :
npm i dotenv - Create the ".env" file and add the STRING_URI variable from MongoDB Atlas
- Be sure to add .env to the .gitignore file if you want to share your project