Node.js interview preparations
Tags: node, interview, crud, theory
Published: 2022-01-23 14:40:03

```
Backend development
Backend refers to the server-side of an application. It generally includes a web server that communicates with a database to serve requests. Java, PHP, Python, and Node.js are some of the backend development technologies.
```
**Node.js**

```
Node.js is an open-source, cross-platform JavaScript runtime environment and library for applications written in JavaScript language. The Node.js driver uses the asynchronous Javascript API to communicate with your MongoDB cluster.

- Node.js is single-threaded for async processing. It means the web requests and processing runs on the same thread.By doing async processing on a single-thread under typical web loads, more performance and scalability.

- Asynchronous code allows the program to be executed immediately where the synchronous code will block further execution of the remaining code until it finishes the current one. This may not look like a big problem but when you see it in a bigger picture you realize that it may lead to delaying the User Interface. So it does not block the rest of the code from executing and after all the code its execution, it gets pushed to the call stack and then finally gets executed. This is what happens in asynchronous JavaScript.
Asynchronous code example: _
<script>
	document.write("Hi");
	document.write("<br>");

	setTimeout(() => {
		document.write("Test");
	}, 2000);

	document.write("<br>");
	document.write("End");
	document.write("<br>");
</script>
**Output:** 
Hi
End
Test
- Synchronous means to be in a sequence, i.e. every statement of the code gets executed one by one. So, basically a statement has to wait for the earlier statement to get executed.
```

```
- Promises
A Promise is an object returned by the asynchronous method call that allows you to access information on the eventual success or failure of the operation that they wrap. The Promise is in the Pending state if the operation is still running, Fulfilled if the operation completed successfully, and Rejected if the operation threw an exception. You can define your own logic that executes once the Promise reaches the Fulfilled or Rejected state by appending the then() method. When you append one or more then() methods to a Promise, each call passes its execution result to the next one. This pattern is called Promise chaining.
_Promise chaining example:_
collection.updateOne({ name: "Mount McKinley" }, { $set: { meters: 6190 } })
  .then(
    res => console.log(`Updated ${res.result.n} documents`),
    err => console.error(`Something went wrong: ${err}`),
  );

the catch() method which accepts a single callback, executed when the Promise transitions to the Rejected state.

_Await:_ If you are using async functions, you can use the await operator on a Promise to pause further execution until the Promise reaches either the Fulfilled or Rejected state and returns. 

- Callbacks
A callback is a method that gets called after another method has finished executing. This allows the enclosing method to continue to execute other commands until the original operation completes. A callback function is called after a given task. It allows other code to be run in the meantime and prevents any blocking.  Being an asynchronous platform, Node.js heavily relies on callback. All APIs of Node are written to support callbacks. Using callback is complex since you end up with several nested callbacks

- asynchronous and non-blocking APIs in Node.js
All Node.js library APIs are asynchronous, which means they are also non-blocking
A Node.js-based server never waits for an API to return data. Instead, it moves to the next API after calling it, and a notification mechanism from a Node.js event responds to the server for the previous API call

```
**commonly used libraries in Node.js**
```
ExpressJS - Express is a flexible Node.js web application framework that provides a wide set of features to develop web and mobile applications. Allows you to define routes of your application based on HTTP methods and URLs. Includes various middleware modules which you can use to perform additional tasks on request and response. Easy to integrate with different template engines like Jade, Vash, EJS etc.
Mongoose - Mongoose is basically a package that serves as a mediator between the NodeJS application and MongoDB server. It is an Object Document Mapper(ODM) that allows us to define objects with strongly-typed-schema that is mapped to a MongoDB document. Mongoose supports all the CRUD operations – Creating, Retrieving, Updating, and Deleting.
body-parser - parses your request and converts it into a format from which you can easily extract relevant information that you may need.
.env file - Its environment variables file. In simple term, it is a variable text file. In this file we set a variable with value that you wouldn’t want to share with anyone, purpose of file is keep as secret and secure because in .env file we store our database password, username, API key etc.
syntax => ENV_VARIABLE=VALUE
```
**modules in Node.js**

```
In Node.js applications, modules are like JavaScript libraries and include a set of functions. To include a module in a Node.js application, we must use the require() function with the parentheses containing the module's name.

```

```
- Http (Hypertext Transfer Protocol) methods
HTTP is an asymmetric request-response client-server protocol as illustrated.  An HTTP client sends a request message to an HTTP server.  The server, in turn, returns a response message.  In other words, HTTP is a pull protocol, the client pulls information from the server (instead of server pushes information down to the client). An HTTP client sends an HTTP request to a server in the form of a request message which has a request method indicates the method to be performed on the resource identified by the given Request-URI. The method is case-sensitive and should always be mentioned in uppercase.

GET - The GET method is used to retrieve information from the given server using a given URI. Requests using GET should only retrieve data and should have no other effect on the data.

HEAD - Same as GET, but transfers the status line and header section only.

POST - A POST request is used to send data to the server, for example, customer information, file upload, etc. using HTML forms.

PUT - Replaces all current representations of the target resource with the uploaded content.

DELETE - Removes all current representations of the target resource given by a URI.

CONNECT - Establishes a tunnel to the server identified by a given URI.

OPTIONS - Describes the communication options for the target resource.

TRACE - Performs a message loop-back test along the path to the target resource.
```

```
- HTTP response
After receiving and interpreting a request message, a server responds with an HTTP response message:

1. A Status-line

2. Zero or more header

3. An empty line

4. Optionally a message-body

HTTP Status Codes
1xx: Informational
It means the request has been received and the process is continuing.
2xx: Success
It means the action was successfully received, understood, and accepted.
3xx: Redirection
It means further action must be taken in order to complete the request.
4xx: Client Error
It means the request contains incorrect syntax or cannot be fulfilled.
5xx: Server Error
It means the server failed to fulfill an apparently valid request.

```
**Node.js CRUD Operations Using Mongoose and MongoDB Atlas
**

```

Install the mongoose and the express module through npm using the below command:

npm install express mongoose --save

Server Setup: Here, we’ll set up our server on port 3000 and call the express function that returns a server object in a variable named app. Then we start the listener saying app.listen with the port address. Finally, we create the /api route which will be triggered once request localhost:3000/api is received from the browser. 
const express=require('express');
const bodyParser=require('body-parser');
const api = require('./api');

const port=3000;
const app=express();

app.listen(port, function() {
	console.log("Server is listening at port:" + port);
});

// Parses the text as url encoded data
app.use(bodyParser.urlencoded({extended: true}));

// Parses the text as json
app.use(bodyParser.json());

app.use('/api', api);
```

```
Schema: Schema is a representation of the structure of the data. It allows us to decide exactly what data we want, and what options we want the data to have as an object.

var mongoose=require('mongoose');

var StudentSchema = new mongoose.Schema({
	StudentId:Number,
	Name:String,
	Roll:Number,
	Birthday:Date,
	Address:String
});

module.exports = mongoose.model(
	'student', StudentSchema, 'Students');
```
```
-----------------------------------------------------------
**Defining Routes using Express**
app.use("/shop", ShopRoute);
app.use('/receipts', ReceiptRoute);

When you make a request to server api, express will search for api route and execute the api

CRUD OPERATIONS

- Create: using .save() to save it to the database
router.route('/signup').post((req, res) => {

    const newShop = new Shop(req.body);

    newShop.save()
        .then(() => res.json('Shop created successfully.'))
        .catch(err => res.status(400).json('Error : ' + err));

});

- Retrieve: To retrieve records from a database collection we make use of the .find() function.
router.route('/').get((req, res) => {

    Shop.find()
        .then((Shop) => { return res.json(Shop) })
        .catch(err => res.status(400).json('Error: ' + err));
});

- Delete: To delete a record from database, we make use of the function .remove()
router.route('/deleteall').delete((req, res) => {
    Shop.findByIdAndDelete(receipt._id)
        .then(() => res.json('All Shops deleted.'))
        .catch(err => res.status(400).json('Error : ' + err));
})

- Update
router.route('/update/:receiptId').post((req, res) => {

    return Receipt.find({ _id: req.params.receiptId }).then(
        data => {
            let Receipt = data[0];

            Receipt.phoneNo = Receipt.phoneNo;
            Receipt.paymentMethod = req.body.paymentMethod;
            Receipt.return = req.body.return;

            Receipt.save()
                .then(() => {
                    res.json('Receipt updated.');
                })
                .catch(err => res.status(400).json('Error : ' + err));
        }
    )

});

```

```
**Mongoose functions**
Mongoose models provide several static helper functions for CRUD operations. Each of these functions returns a mongoose Query object. When executing a query with a callback function, you specify your query as a JSON document.

Model.deleteMany()
Model.deleteOne()
Model.find()
Model.findById()
Model.findByIdAndDelete()
Model.findByIdAndRemove()
Model.findByIdAndUpdate()
Model.findOne()
Model.findOneAndDelete()
Model.findOneAndRemove()
Model.findOneAndReplace()
Model.findOneAndUpdate()
Model.replaceOne()
Model.updateMany()
Model.updateOne()
```