MongoDB CRUD Operation with Node.js

Once you get your head around MongoDB CRUD operations with Mongo Shell, getting Node.js to do them becomes easy. If you are still not confident with MongoDB, check out MongoDB skills essentials exercise to brush up your MongoDB skills.

We will create a collection called, students. Then, we will insert records, update a record, remove a record and query all records in a single go. You can use the same syntax as what you would use in Mongo Shell in Node.js. The biggest difference is that each function is asynchronous and you have to use a callback function with the error-first signature.

By doing all the CRUD operations in one go, you get to do a lot of callbacks. It will be fun.

Here comes the code!

const MongoClient = require('mongodb').MongoClient
const url = 'mongodb://writer:Password1@localhost:27017/admin'

// Data
const initialData = [{
   studentId:1,
   firstName:'John',
   lastName:'West',
   Major:'Psychology'
},{
   studentId:2,
   firstName:'Allen',
   lastName:'Doe',
   Major:'Science'
},{
   studentId:3,
   firstName:'Shane',
   lastName:'West',
   Major:'IT'
}]

// (1) Insert the initial data
const insertStudent = (collection, callback) => {
    collection.insert(initialData, (err, result) => {
        if (err) {
            console.error(`Insertion error ${err}`)
            process.exit(1)
        } 
        console.log(`No of records: ${result.result.n}`)
        callback(result)
    })
}

// (2) Update John's Major to Literature
const updateStudent = (collection, callback) => {
    collection.update({studentId:1},{$set:{Major:'Literature'}}, (err, results) => {
        if (err) {
            console.error(`Update error: ${err}`)
            process.exit(1)
        }
        console.log(`Record updated successfully.`)
        callback(results)
    })
}

// (3) Remove studentId=3
const removeStudent = (collection, callback) => {
    collection.remove({studentId:3}, (err, results) => {
        if (err) {
            console.error(`Remove record error: ${err}`)
            process.exit(1)
        }
        console.log(`Record removed successfully.`)
        callback(results)
    })
}

// (4) Query all records
const getStudents = (collection, callback) => {
    collection.find({}).toArray((err, data) => {
        if (err) {
            console.error(`Cannot find student records: ${err}`)
            process.exit(1)
        }
        console.log(`Record count: ${data.length}`)
        console.log(data)
        callback(data)
    })
}

// (5) Put them all together
MongoClient.connect(url, (err, client) => {
    if (err) {
        console.error(`Connection Error: ${err}`)
        return process.exit(1)
    }
    console.log(`Connection Successful`)
    const db = client.db('usermanaged')
    const collection = db.collection('students')
    insertStudent(collection, () => {
        updateStudent(collection, () => {
            removeStudent(collection, () => {
                getStudents(collection, () => {
                    client.close()
                    console.log('DB connection closed.')
                })
            })
        })
    })
})
Front-End
TypeScript: type aliases to check type equality

This post is to analyse how the type equality check by using type aliases proposed by Matt Pocock in his twitter post. These type aliases allow us to elegantly express type equality checks in unit tests. All we need to do is to pass the output and expected types in …

Front-End
Fixing it.only type error in Jest

If you are getting a type error with it.only in Jest, it could be due to incorrect TypeScript typings or incompatible versions of Jest and TypeScript. To resolve this issue, you can try the following steps: Make sure you have the latest versions of Jest and its TypeScript typings installed …

Front-End
yup conditional validation example

Here’s an example of a Yup validation logic where the first input field is optional but, if filled, it must contain only alphabetic characters, and the second input field is required: import * as Yup from “yup”; const validationSchema = Yup.object().shape({ firstField: Yup.string().matches(/^[A-Za-z]*$/, { message: “First field must contain only …