How to Prevent Creating Duplicate Keys in MongoDB

In MongoDB, the primary key is reserved for the _id field. This is a system field and gets created by default when inserting new records. When you want to enforce the uniqueness in other fields, you can use unique index.

Here is how to create unique index with Mongo Shell. Unique key can be a compound key. You can use getIndexes() to get indexes on the collection.

# (1) Single
db.students.createIndex( { "studentId": 1 }, { unique: true } )

# (2) Compound
db.students.createIndex(
    { "studentId": 1, lastname: 1, firstname: 1  },
     { unique: true } )

# (3) Get indexes
db.students.getIndexes()

Now, let’s check out how it can be done with Node.js. In Node, you can use createIndex() as in the Mongo shell. As usual, it is asynchronous and you need a callback function with the usual error-first signature.

When you first run the code, it inserts the records and create unique index on the studentId field. When you run it for the second time and try to insert the same records, you will get an error on insertion because it is violating the unique index rule.

// Setting up
const MongoClient = require('mongodb').MongoClient
const url = 'mongodb://yourUsername:yourPassword@localhost:27017/admin'

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

// function to create uniqe index
const uniqueIndex = (collection, callback) => {
    collection.createIndex({studentId:1}, {unique:true}, (err, result) => {
        if(err) {console.error(`Failed to create index ${err}`); process.exit(1);}
        console.log(`Unique Index created successfully: ${result}`)
        callback(result)
    })
}

// function to insert student records
const insertStudents= (collection, callback) => {
    collection.insert(initialData, (err, result) => {
        if (err) {
            console.error(`Error in insertion: ${err}`)
            process.exit(1)
        }
        console.log(`No of records (result.result.n): ${result.result.n}`)
        console.log(`No of records (result.ops.length): ${result.ops.length}`)
        callback(result)
    })
}

// put them all together
MongoClient.connect(url, (err, client) => {
    if (err) return process.exit(1)
    console.log('Connection successful.')
    const db = client.db('usermanaged')
    const collection = db.collection('students')
    insertStudents(collection, () => {
        uniqueIndex(collection, () => {
            client.close()
            console.log('Connection closed')
        })
    })
})

REFERENCE

Git
How to specify which Node version to use in Github Actions

When you want to specify which Node version to use in your Github Actions, you can use actions/setup-node@v2. The alternative way is to use a node container. When you try to use a publicly available node container like runs-on: node:alpine-xx, the pipeline gets stuck in a queue. runs-on is not …

AWS
Using semantic-release with AWS CodePipeline and CodeBuild

Here is the usual pattern of getting the source from a git repository in AWS CodePipeline. In the pipeline, we use AWS CodeStart to connect to a repo and get the source. Then, we pass it to the other stages, like deploy or publish. For some unknown reasons, CodePipeline downloads …

DBA
mysqldump Error: Unknown table ‘COLUMN_STATISTICS’ in information_schema (1109)

mysqldump 8 enabled a new flag called columm-statistics by default. When you have MySQL client above 8 and try to run mysqldump on older MySQL versions, you will get the error below. mysqldump: Couldn’t execute ‘SELECT COLUMN_NAME, JSON_EXTRACT(HISTOGRAM ‘$”number-of-buckets-specified”‘) FROM information_schema.COLUMN_STATISTICS WHERE SCHEMA_NAME = ‘myschema’ AND TABLE_NAME = ‘craue_config_setting’;’: Unknown …