Create a Node and MongoDB CRUD API

Create a Node and MongoDB CRUD API

Building APIs is essential learning when creating applications. In the Jamstack world, we need APIs to connect to a database to store data.

Let's create an API with Node, Express, and MongoDB.

This is a beginner tutorial that will show you how to create a foundation for an API. This is a great exercise to learn how to build an API from scratch. Once you understand how to build APIs, you can take this even further for larger more robust applications.

We'll be using the MongoDB driver. You may see tutorials that use a tool called mongoose, but there's a lot of flexibility with using the MongoDB driver directly. Here's a good article on mongoose vs mongodb.

We will create a function to connect and also cache the connection. Create a new file (we'll call ours utils/mongodb.js and add the following:

💯Tip
This is the main code snippet you can take and use in all your projects.
javascript
// utils/mongodb.js

const { MongoClient } = require('mongodb');

// get environment variables for database uri and database name
let uri = process.env.MONGODB_URI
let dbName = process.env.MONGODB_DB

// create cache variables so we can cache our connection
let cachedClient = null
let cachedDb = null

// function to connect to the database
// returns an object with the { client, db }
module.exports = async function connectToDatabase() {

  // if we already have stuff in cache, use that
  if (cachedClient && cachedDb) {
    return { client: cachedClient, db: cachedDb }
  }

  // connect to mongodb
  const client = await MongoClient.connect(uri, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
  })

  // connect to our specific database
  const db = await client.db(dbName)

  // store the stuff in cache
  cachedClient = client
  cachedDb = db

  return { client, db }
}

Now we can use this in any of our Node files within an Express route:

javascript
const { connectToDatabase } = require('./utils/mongodb.js')

// sample express route to get all posts
app.get('/posts', async (req, res) => {

  // connect to the database
  const { db } = await connectToDatabase();

  // go get all the posts
  const posts = await db
    .collection("posts")
    .find({})
    .limit(20)
    .toArray();

  // send the posts back
  res.json(posts);
});

Next up, we'll handle CRUD operations. These are the HTTP verbs and routes we'll have for our API.

OperationRoute
CreatePOST /posts
ReadGET /posts
UpdatePUT /posts/:id
DeleteDELETE /posts/:id

Take a look at the MongoDB Client methods.

Create Docs using insertOne()

javascript
// create a post
app.post('/posts', async (req, res) => {
  const { db } = await connectToDatabase();

  const posts = await db
    .collection('posts')
    .insertOne(req.body);

  res.json(posts);
});

Find Multiple Docs using find()

javascript
// get all
app.get('/posts', async (req, res) => {
  const { db } = await connectToDatabase();

  // go get all the posts
  const posts = await db
    .collection("posts")
    .find({})
    .limit(20)
    .toArray();

  res.json(posts);
});

Find One Docs using findOne()

javascript
// get a single post
app.get('/posts/:postId', async (req, res) => {
  const { db } = await connectToDatabase();

  const post = await db
    .collection("posts")
    .findOne({ _id: req.params.postId });

  res.json(post);
});

Update Docs using updateOne()

javascript
// update by the post id
app.put('/posts/:postId', async (req, res) => {
  const { db } = await connectToDatabase();

  // update using $set
  const post = await db
    .collection("posts")
    .updateOne(
      { _id: req.params.postId }, // the way we find the document
      { $set: { title: req.body.title } } // the things to update
    );

  res.json(post);
});

Delete Docs using deleteOne()

javascript
// delete by the post id
app.delete('/posts/:postId', async (req, res) => {
  const { db } = await connectToDatabase();
  await db
    .collection('posts')
    .deleteOne({ _id: req.params.postId });

  res.json('Deleted!');
});

We will need the cors package to let Express know that we should allow requests from external domains. Usually essential when building an API since your frontend will be on a different domain.

bash
npm i cors

Use the cors package:

javascript
const cors = require('cors')

// tell express to use the cors middleware
app.use(cors())

Express needs to be told that it will be receiving JSON data in requests. We use express.json() so that Express knows to parse any Content-Type: application/json requests.

javascript
// configure our app -----------------
app.use(express.json()); // make sure express can parse json data

There are many things to add onto your API like authentication/authorization, payments, social login, validation, and more.

If you wanted a more robust solution, you could look at Node frameworks that excel at building applications and APIs like Strapi and Adonis.

Chris Sev

Chris Sev

Chris Sev is the co-founder of Better Dev. Coding better every day. Previously he created Scotch.io which was acquired.

In this article...

Comments

What did you think of the article? Let us know!
(these comments are powered by GitHub issues and use 0 trackers)