Skip to content

Instantly share code, notes, and snippets.

@jeromeabel
Last active February 14, 2023 10:10
Show Gist options
  • Select an option

  • Save jeromeabel/c0981f2729601632438b21e06ddaf8f5 to your computer and use it in GitHub Desktop.

Select an option

Save jeromeabel/c0981f2729601632438b21e06ddaf8f5 to your computer and use it in GitHub Desktop.
Node And MongoDB Primer

Node And MongoDB Primer

Installation

  • Install Node
  • Install MongoDB Driver locally or create a MongoDB Atlas account (see below)
  • Optional : install Compass

Create a project

$ mkdir project && cd project
$ npm init -y
$ npm i mongodb

Create a local database

Create 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()

First connection & list resources

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);

List databases

const databasesList = await client.db().admin().listDatabases();
console.log('DATABASES');
databasesList.databases.forEach((db) => console.log(`- ${db.name}`));

List collections

const collections = await client.db('blog').listCollections().toArray();
console.log('COLLECTIONS : ', collections);

Create a resource

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}`);

Create a resource with the body

const results = await client.db('blog').collection('posts').insertOne(req.body);
res.status(201).send(results);

MongoDB Atlas

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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment