Quickly Connect To MongoDB In NodeJS

14 Jun 2020 - Andrew McCall

I will get quickly to the point.

const express = require("express");
const app = express();
const mongodb = require("mongodb");
const router = require("./router");
let db;

connectionString =
  "your mongo connection string here"

app.set("views", "views");
app.set("view engine", "ejs");

app.use(express.urlencoded({ extended: false })); //  boilerplate to initialize req.body.input-name
app.use("/", router);
app.use("/thanks", router);

  { useNewUrlParser: true, useUnifiedTopology: true },
  function (err, client) {
    db = client.db();
    app.listen(port number);
  1. make sure node.js is installed on your system.
  2. start a new project.
  3. using terminal, cd into project directory.
  4. npm init -y create app.js
  5. You need to know your mongodb database name and collection
  6. npm install mongodb
  7. in app.js require and initialize express.
  8. require mongodb and initialize routes if available
  9. initialize db variable.
  10. to get form data you need to use the express.urlencoded feature to get req.body.input-name
  11. monbodb.connect takes 3 arguments connectionstring (from mongodb), an object, and then a function
  12. make sure to establish database connection before listening on the port

These are quick and dirty notes for communicating with the database server.

chevron_left Console.Log A Chessboard
Recursive Functions chevron_right
Tags: javascript, web development