MongoDB, from Node.js

We have seen access to the server file system fron node with the fs module. Now we shall look at using a database for our data persistence needs. Normally we use the acronym CRUD as a general term for that. CRUD is from the SQL terminology, but applies really to all database systems as a concept.

C
Create, ie write an entry into a database, in casu a document into a database collection. In mongodb the function is insert().
R
Retrieve, ie read an entry from a database, in casu a document from a database collection. The mongodb function is find().
U
Update, ie update an entry in a database, in casu a document in a database collection.
D
Delete, ie delete an entry from a database, in casu a document in database collection.

To do any of the above we must always establish a connection to the database from out code. It is done as follows:

Example 19.1. Connect to a MongoDb Database from Node.js, dbConnect12.js
/*
 * File Name is  : dbConnect12.js
 * demoes connection til mongo
 */
'use strict';

const mongo = require('mongodb');
const dbname = "world";
const constr = `mongodb://localhost:27017`;
const conparam = { useNewUrlParser: true, useUnifiedTopology: true };
mongo.connect(
    constr, conparam, function (error, con) {
    if (error) {
        throw error;
    }
    console.log(`Connected to server`);
    const db = con.db(dbname);
    // do stuff
    con.close();
});

Now try to run:

node dbConnect12

Technically you don't create a database, but connect to the database server pointing at the specified database which incidentally doesn't exist in any physical sense until there's data in it.


In the following we shall see examples of CRUD from node.

Create/Update

Example 19.2. Insert into a MongoDb Database with Node.js, insertCity12.js
/*
 * File Name is  : insertCity12.js
 * demoes inserts into a mongo collection
 */
'use strict';

const mongo = require('mongodb');
const dbname = "world";
const constr = `mongodb://localhost:27017`;
const conparam = { useNewUrlParser: true, useUnifiedTopology: true };
mongo.connect(
    constr, conparam, function (error, con) {
    if (error) {
        throw error;
    }
    console.log(`Connected to server`);
    const db = con.db(dbname);                  // make dbname the current db
    /* Create,
     * inserts cities into the database
     */
    let obj = { name: "Aarhus", countrycode: "DNK", district: "Østjylland", population: 284846 };

    db.collection("city").insertOne(obj, function (err, collection) {
        if (err) {
            throw err;
        }
        console.log("City inserted");
        con.close();
    });
});

Now try to run:

node insertCity12

Example 19.3. Update/Insert with Check, updateCity121.js
/*
 * File Name is  : updateCity12.js
 * demoes inserts or updates a mongo collection
 */
'use strict';

const mongo = require('mongodb');
const dbname = "world";
const constr = `mongodb://localhost:27017`;
const conparam = { useNewUrlParser: true, useUnifiedTopology: true };
let data = process.argv[2];
let obj = JSON.parse(data);
let que = {name: obj.name};

mongo.connect(
    constr, conparam, function (error, con) {
    if (error) {
        throw error;
    }
    console.log(`Connected to server`);
    const db = con.db(dbname);                  // make dbname the current db
    /* Update,
     * updates/inserts city in the database
     */

    db.collection("city").updateOne(
        que, {"$set": obj}, {upsert: true}, function (err, collection) {
        if (err) {
            throw err;
        }
        console.log("City inserted/updated");
        con.close();
    });
});

Now try to run:

node updateCity121 '{ "name": "Kolding", "countrycode": "DNK", "district": "Syd", "population": 70000 }'
node updateCity121 '{ "name": "København", "countrycode": "DNK", "district": "Østsjælland", "population": 495699 }'
node updateCity121 '{ "name": "Odense", "countrycode": "DNK", "district": "Syd", "population": 183912 }'
node updateCity121 '{ "name": "Suburbia", "countrycode": "DNK", "district": "Øst", "population": 12345 }'

Retrieve

Example 19.4. Read a MongoDb Database with Node.js, findCity12.js
/*
 * File Name is  : findCity12.js
 * demoes reading one item a mongo collection
 */
'use strict';

const mongo = require('mongodb');
const dbname = "world";
const constr = `mongodb://localhost:27017`;
const conparam = { useNewUrlParser: true, useUnifiedTopology: true };
let que = JSON.parse(process.argv[2]);

mongo.connect(
    constr, conparam, function (error, con) {
    if (error) {
        throw error;
    }
    console.log(`Connected to server`);
    const db = con.db(dbname);                  // make dbname the current db
    /* Retrieve,
     * reads cities from the database
     */
    db.collection("city").find(que).toArray(function (err, city) {
        if (err) {
            throw err;
        }
        console.log(city);
        con.close();
    });
});

Now try to run:

node findCity12 '{ "name": "Kolding" }'

Example 19.5. Read a MongoDb Database with Node.js, findCity121.js
/*
 * File Name is  : findCity12.js
 * demoes reading all in a mongo collection
 */
'use strict';

const mongo = require('mongodb');
const dbname = "world";
const constr = `mongodb://localhost:27017`;
const { useNewUrlParser: true, useUnifiedTopology: true };

mongo.connect(
    constr, conparam, function (error, con) {
    if (error) {
        throw error;
    }
    console.log(`Connected to server`);
    const db = con.db(dbname);                  // make dbname the current db
    /* Retrieve,
     * reads cities from the database
     */
    db.collection("city").find().toArray(function (err, city) {
        if (err) {
            throw err;
        }
        console.log(city);
        con.close();
    });
});

Now try to run:

node findCity121

Delete

Example 19.6. Delete from a MongoDb Database with Node.js, deleteCity12.js
/*
 * File Name is  : deleteCity12.js
 * demoes deleting one item from a mongo collection
 */
'use strict';

const mongo = require('mongodb');
const dbname = "world";
const constr = `mongodb://localhost:27017`;
const conparam = { useNewUrlParser: true, useUnifiedTopology: true };

let que = JSON.parse(process.argv[2]);

mongo.connect(
    constr, conparam, function (error, con) {
    if (error) {
        throw error;
    }
    console.log(`Connected to server`);
    const db = con.db(dbname);                  // make dbname the current db
    /* Retrieve,
     * reads cities from the database
     */
    db.collection("city").deleteOne(que, function (err, city) {
        if (err) {
            throw err;
        }
        console.log(`delete ${que.name}`);
        con.close();
    });
});

Now try to run:

node deleteCity12 '{ "name": "Suburbia" }'