Prior to writing this article, I spent a lot of time searching the web for beginner friendly Node.js +mongoDB tutorials. This aspect of the tutorial is very many, but for a novice is not friendly, the purpose of this article, is to let a small white can achieve a step by step using Node +mongoDB to create a server of their own, so our full stack road from here to start

Git address https://github.com/foreverway/node-express-mogoDB.git

What is the Node. Js

As a server-side language, Node.js uses the JS syntax, but it doesn't mean you can use it directly. When we open the official Node.js documentation, we'll see that it focuses on Node features and apis

As a novice worth your salt, I'm guessing you'll close this page in ten minutes. Since learning is a gradual process, it's a good idea to start with a simple demo through the framework and get to know Node.js. Because a lot of features, only when it is in the use of understanding, learn much strange new things at the beginning, let us bewilder framework will be many, on the one hand, we want to quickly get started, on the other hand also want to retain the original characteristics of the language, the framework of excessive packaging, may hurt our understanding of the node, there are express, Egg.js.next. Js etc. Here, I choose Express to get started

Use the command line to install the Express framework and initialize the project. Open the Express folder and create a JS file, such as server.js

In the server.js file, refer to Express

//require ('express ') const app = express(); //require ('express '); App.listen (3000,()=>{console.log(' app is listening on port 3000 '))}) Start project node server (server.js suffix can be left out)Copy the code

So let's write a definition of the get method that takes two parameters, the first is a path, and the second is a function. Okay

App.get ('/',function(req,res){res.send('hello') //responseCopy the code

Go to http://localhost:3000/ That doesn't seem like much, so replace the send output with an array of objects

[{name:' morning ',provience:' Guangdong '}, {name:'xiaomi Xiaoming ',provience:' Taiwan '}] // Restart a server node serverCopy the code

The array data we request from the back end is like this, at this time you may think it is too troublesome to restart every change, so at this time we change to Nodemon (Nodemon Server) to start, so that it will automatically listen to our changes. With that in mind, we can try to write more interfaces

App. Get ('/', function (the req, res) {res. Send ([{name: 'we', provience: 'guangdong'}, {name: xiao Ming, provience: 'Taiwan'})}) app. Get ('/shoppingList ', function (the req, res) {res. Send ([{id: '1', provience: 'Gift A'}, {id:'2',provience:'Gift B'}, {id:'3',provience:'Gift C'} ]) }) app.get('/home',function(req,res){ res.send('this is my home') })Copy the code

So when we visithttp://localhost:3000/home So when we visithttp://localhost:3000/shoppingList

Managed static files

Using the above method, we can respond to the user to visit the url, but we sometimes want to access the content of other pages, when we need to implement a route

app.use(express.static('public')) We add this middleware to server.js, which is dedicated to hosting static files. We use this file that has access to the public path to create a new public file, and then create an index.html, whatever

2, visithttp://localhost:3000/index.html

3· Of course, we can also put it in other paths. The default path of app.use() is the root path, and we can also set the path ourselves.

app.use('/static',express.static('public'))

Then you need to can access to http://localhost:3000/static/index.html

To deal with cross domain

We first request the data we just created in the index.html file we just created in public

Fetch (' http://localhost:3000/shoppingList '). Then (res = > res. Json () / / convert the data into a json format). Then (res = > {the console. The log (res)})Copy the code

Open the http://localhost:3000/static/index.html, the data in the Network can see received

Everything looks perfect because we have the same domain name, port, protocol. There will be no cross-domain problems if in the previous step, someone used itopen with live serverThis plugin, it opens based on the local IP addressThis page, by the wayNginx reverse proxy and CORS allow cross-domain headers. In Express, it is easier to use CORS, and there is a corresponding NPM package to help us handle this mattercnpm i cors -S

Use (require(‘cors’)()))// to use this module directly in server.js.

Connect to the mongoDB database

Although we have available at the front page node. Js data generated, but such changes in the data every time we need to manually change, so only suitable for oneself of pure show mock data, daily development, our data in the database, the database is not tall, the concept of you I think it's just a storage of data warehouse, We can add and delete statements to query the data we want in the node is used in the more mongo, database also has local and online, when we don't have their own cloud service period, we can only put the data in the local Only he could get to like this, have their own cloud server can be placed above

We will briefly talk about mongoDB here. First of all, we need to download a package mongoose to connect to the database in Node.js

npm i mongoose -S

Linking databases again we need to introduce this package in server.js

Const mongoose = require('mongoose') mongoose. Connect ('mongoose://localhost: 27017/ShoppingList') // the first parameter is the address of the database, which is in the format of mongoDB:// start + database IP address + port number default 27017+/ / if the data set does not exist, We're connecting to the ShoppingList data set. In this case, we're the local database, so the address is either localhost or 127.0.0.1Copy the code

So when we do that, we start it up, and it’s going to report an error, because it’s missing some parameters, and we’re going to add it as prompted

const mongoose = require('mongoose') mongoose.connect('mongodb://localhost:27017/ShoppingList', { useNewUrlParser: True,useUnifiedTopology:true}) this is the code for linking the databaseCopy the code

Next we need to define a model (called a collection in mongoDB), which is a classification of the data in the database. Each model contains our corresponding data. For example, we now have a shoppingList model

Const shoppingList = mongoose. Model (' shoppingList ',new mongoose.Schema({title:String}) The second argument is a table structure, and it takes an object, such as the title property, whose value is the type of the value, such as StringCopy the code

So we can use it first. Let’s connect the interface of our ShoppingList to the database

App.get ('/shoppingList',async function (req, res) {res.send(await shoppinglist.find ()) find() Because connecting to the database is an asynchronous operation we use async and await to get the value of our database synchronously})Copy the code

Of course, since there’s no data in the database, we can temporarily insert some data for observation, so let’s write one under this interface

ShoppingList. InsertMany ([{title: 'computer 1}, {title:' computer 2}, {title: 'computer 3},])Copy the code

So with insertMany, we're just going to insert the following data into the database, save it, and see what happens. If you save it multiple times, you're going to get more and more data, because this insert is going to be repeated so we can comment it out after we insert it Access the connection address and you can see the data we just inserted. The extra _id indicates that the identity of each value is automatically generated, and __v indicates the version of the data

Mongo query

We have just done a query of the database data, but it is clear that there is a lot of work to do, such as paging, there is a value to query for certain conditions

So let’s change the query

App.get ('/shoppingList',async function (req, res) {// const data = await shoppinglist.find ().limit(2) //limit as he means, Const data = await shoppinglist.find ().skip(1).limit(2) //skip skip, const data = await shoppinglist.find ().skip(1).skip(2) This shows 2.3 and skips 1. // const data = await shoppinglist.find (). Where ({title:' computer 1'}) //sort(_id:1/-1) Res. send(data)Copy the code

There is often a need to view the details of an item where we can provide a dedicated interface to return the data

app.get('/shoppingList/:id',async function (req, Res) {//# : const data = await shoppingList.findByid (req.params.id) //findById = await shoppingList.findById Req. Params req. Params req. Params res.send(data) //res req.Copy the code

It looks like this

As you may have noticed earlier, all of our interfaces are done using get, but sometimes we need to send some data that’s too big for a URL, We need to use the POST method // to add data to the list interface // we just used the code’s insertMany method to insert data, now we use POST to do that

App.post ('/shoppingList',async function (req, res) {const data = {} // Upload an empty object res.send(data)})Copy the code

Now go to the original page and request this dataYou’ll find that you’re still accessing the original get interface, because their address is the same. Here we download an extension in vscoderest client He helps us use code to make different types of HTTP requestsOnce the download is complete, we’ll create a new file in the root directory with whatever name we want, but the suffix should be HTTP and we’ll start with the get method and add the link we just did

get http://localhost:3000/shoppingList

And then it says Send Require and if we click on that, you can see the message that the server is sending backSo if we have multiple interfaces, how do we write it? First of all, the interfaces have to be separated by ###, and then we can define the common parts, not every time We know that there are many types of data. If the specifications of the front and back end are inconsistent // we will report 415 error, so we need to standardize the data type here

Content-type :application/json Remember to follow the POST command line

// If you use a library like Axios, you don't need to add // we specify that you send data in JSON format, remember JSON is in double quotes and then use this post to send a data

Ah? The data still hasn’t come up. Because the server didn’t receive the request we submitted here, we rewrote the POST request to the server.js page

App. post('/shoppingList',async function (req, res) {const data =req.body //req.body. //req.body indicates the data submitted by the client, res.send(data)})Copy the code

JSON file parsing is not enabled by express by default. We need it in server.jsconst app = express()After any position plusapp.use(express.json()))Indicates that we allow him to parse the submitted data in JSOP format

Try again and you can get the post dataWith that said, let’s get back to the title: How to store POST data into a database in the first placeconnect.http, here is just to simulate the client to send data, equivalent to the user upload part, here we have no way to contact the database, can only be carried out in the server, that is, we corresponding POST request rewrite POST request

app.post('/shoppingList',async function (req, Res) {const data = req.body const shopping =await shoppingList.create (data) To create data, use create to store in the ShoppingList collection, remember to use await res.send(shopping)})Copy the code

Try once before sendingSaved to the database successfully Set the query database interface to query all

// View the list interface

app.get('/shoppingList',async function (req, res) {
    const data = await ShoppingList.find()
    res.send( data)
})
Copy the code

Click the Send request

The data is already stored in the database. Other types of requests typically, we use GET to get the data, POST to send the data, and when we modify, we use PUT to submit our request and here's how to use PUT. In fact, PUT is similar to the interface for viewing details, because we find a certain piece of data through attributes such as ID and perform operations

App. put('/shoppingList/:id',async function (req, res) {//put indicates overwrite, Const data = await shoppingList.findByID (req.params.id) data.title = req.body.title // Modify await according to the value passed in by the client Data.save () // Save changes res.send(data)})Copy the code

Then in the connect.http file, we say put interface

PUT {{uri}} shoppingList / 5 f53bb006e15a80b2c4bdb7c content-type: application/json {" title ":" 1010 "computer} / / list and then check the product databaseCopy the code

As you can see, the values in the database have been modified and similarly, we can easily get rid of them

// Delete a data app.delete('/shoppingList/:id',async function (req, res) { const data = await ShoppingList.deleteOne({id:req.body.id} res.send( data) }) connect.http DELETE {{uri}} shoppingList / 5 f538c6054c5512be4876208 content-type: such is application/json, executed, you also found that the data of database has been deletedCopy the code

The VUE project connects to the database

So far, our basic work is done here, so how to use it in the actual project

I’ll talk about that in the next article

Reference source

Station B: Top of the stack

Add, delete, and overcheck mongoDB connection database