MongoDB, Node.JS and API

Hari Kishore
2 min readApr 14, 2020

I recently happened to create a node app with simple functionality. It included all those basic component of a typical app. It had a database ( mongoDB, to be precise on cloud), Node.JS as server side scripting and was using express.js for routing and stuffs. Connection to database was handled using mongoose.js library. and all the transactions were being done using RESTful APIs. After all the code were done and working properly, the thought of putting it online came to mind and I used Heroku for that. MongoDB was internally using (hosted on) AWS cloud services. The Code was hosted on GitHub online repository and SCM was also Git. And in last, while I am counting, lets also not forget VSCode, where all coding was being done.

Key Takeaway —

  1. String type — while defining database schema — Yes, strings in MongoDB have unlimited length (up to document max size, of course (16MB))[1]
  2. GitHub CI (Continuous Integration) — [yet to know more]
  3. MongoDB - ObjectId— An ObjectId is a 12-byte BSON type having the following structure −
  • The first 4 bytes representing the seconds since the unix epoch
  • The next 3 bytes are the machine identifier
  • The next 2 bytes consists of process id
  • The last 3 bytes are a random counter value

MongoDB uses ObjectIds as the default value of _id field of each document, which is generated while the creation of any document. The complex combination of ObjectId makes all the _id fields unique.

4. Heroku Deployment — Easiest with github. also, If you need to change anything in code, you can change it on github and changes will be reflected in Heroku Launched App. (So, Use it as free server)

5. Nested Documents —

In real world the data is not so simple. One-to-many and other relations are there. for example-

{
name:'hari',
age:20,
address:{
city: chennai,
country: India,
pincode: 600032
}
}

So, to model such data we can do so —

Author Schema

6. Environment Variable — used to hide your secret data. Also, Environment variables are used in applications in order to have different behaviour for different environments.

  • Data Secrecy — Instead of $username:'root123' and $password:'MySecretPassword' , You can write as ,
$username = process.env.USER_NAME;
$password = process.env.PASS_WORD;

And, this variable is safe with the OS only. Only OS can read these variables and (other library with the help of OS modules only).

7. GitHub gist — Gists are code snippet to showcase or use or share with someone. The above code you see from github is a Git gist.

8. Well formated JSON response —

  res.header("Content-Type",'application/json');
res.send(JSON.stringify(results, null, 4));

--

--