Connect to MongoDB with Nodejs

Tram Ho

1. Introduction:

MongoDB is one of the most popular NoSQL open source databases known by C ++. As of February 2015, MongoDB is ranked fourth among the most popular database systems. It was developed by 10gen company later known as MongoDB Inc.

MongoDB is a document-oriented database, which stores data in JSON documents with dynamic schema very flexibly. This means that you can save records without worrying about the data structure such as the number of fields or type of storage field. MongoDB documents are similar to JSON objects.

In MongoDB, data is stored as a document, a set of key-value pairs. You can define multiple databases in MongoDB and each database has many collections, these collections are simply a collection of documents stored as key-value pairs.

2. Connect with MongoDB:

  • Install Mongoose
  • Install mongodb
  • Set up mongod if you don’t know (read this article)
  • Make sure mongodb is running with the localhost server

3. Create a schema:

MongoDB is a document database, it stores JSON as objects. The model / schema describes what these objects contain.

The schema describes the fields we have in the form and specifies the data it expects

Example 1 model as follows:

Here we can specify the validation for the model data, as you can see in the usernam I have specified it as required, only alphanumeric is allowed, and the minlength must be 6 characters for example.

4.Insert the data into MongoDB:

  • Add middleware body-parser to parse the body of requests to the server
  • Create a POST route for sending data to the server
  • Stored values ​​and stored in db with schema

5. Select data from MongoDB:

6. Update MongoDB data:

Share the news now

Source : Viblo