# [TIL] Node Express Server HW1

## Issues encountered

1. Error:
    

```bash
MongoServerError: E11000 duplicate key error collection: voyage_blog.posts index: postId_1 dup key: { postId: null } ...
at writeOrBuffer (node:internal/streams/writable:389:12) {
index: 0,
code: 11000,
keyPattern: { postId: 1 },
keyValue: { postId: null },
[Symbol(errorLabels)]: Set(0) {}
}
```

1. Performed a find operation and sorted by createdAt in descending order based on createdAt.
    
2. Is it correct to handle initial validation for request values coming from params or body with if statement, checking if they are of string type and have valid values? Since type and required are already defined in the schema, is it enough to handle it with just try-catch statements?
    
    ```javascript
    const { password, title, content } = req.body;
    const { _postId } = req.params;
    if (
        typeof password !== "string" ||
        typeof title !== "string" ||
        typeof content !== "string" ||
        !_postId
    ) {
        return res.status(400).json({
        errorMessage: "Data format is incorrect.",
        });
    }
    ```
    

## What I Tried

1. I used `ObjectId` in MongoDB to differentiate between posts and comments by automatically assigning a unique id to each document when it is created. Since MongoDB automatically assigns this `_id`, I did not create a key for id in the schema. However, I encountered the above error every time I tried to POST more than one document.
    
    1. **Error analysis**: The error occurred because the postId key in the posts collection had a value of null in the first document, and {postId: null} was continuously added when registering other documents, resulting in a duplicate for the postId of the first document.
        
    2. **Problem cause**: When designing the database initially, I created the postId key and it existed with a null value on the table, although it was not visible on the schema.
        
    3. **Problem resolution**: I dropped the posts collection in the DB and re-sent the POST request, and it worked correctly.
        
2. `createdAt` can be used in the schema to sort in descending order with `sort({ createdAt: "desc" })`.
    
3. It is not recommended to catch all error cases with catch. In addition, even though frontend handles these exception handling, it is better to handle as much as possible on the server side and return immediately before performing other events. In other words, it is appropriate to handle it as I did. Also, there may be cases where the input values do not cause errors but do not meet the conditions, so it is better to handle them with if statements. However, as you learn more about Node.js server, you will come to understand that these error/exception handling are managed by dividing them into layers/modules according to functionality through 3-layer architecture. In other words, instead of handling all error/exception handling, server processing, etc. in the router as I did now, the server should be designed by dividing it into router (controller), data access, and service layers. Also, it is used for handling boilerplate code that is common in multiple files.
    

![](https://miro.medium.com/v2/resize:fit:828/format:webp/1*TDEwPm0dZbOSzip5K3nhKA.jpeg align="left")

* The Controller parses/validates the request and passes it to the service layer.
    
* The Service layer performs application-specific tasks according to the business logic.
    
* Data Access interacts with the database by performing queries.
    

## How I Resolve the Issues

1. I dropped the posts and comments collections in the DB and re-sent the POST request, and it worked correctly.
    
2. `const posts = await Posts.find({}).sort({ createdAt: "desc" })`
    
3. It is necessary to handle errors/exceptions as quickly as possible on the server side and return early if conditions are not met. While the code in the schema may specify the type and required fields, it's still a good idea to perform additional validation and error handling in the router (controller) to ensure that the input data meets the expected format and values. This helps to catch potential issues early and provide appropriate error responses to the client.
    

## What I newly learned

1. 3-layer architecture
    
2. AWS EC2 deployment
    

## What to learn next

1. Authentication
    
2. SQL
    
3. Sequelize
