Magren

Magren

Idealist & Garbage maker 🛸
twitter
jike

Writing interfaces with node.js+express

I recently studied how to use node.js to operate MongoDB databases, and now I am adding a record on writing interfaces.

Connect to the database#

Install Mongoose in the project root directory

npm install mongoose --save

Use Mongoose to connect to MongoDB and create a db.js file in the project:

'use strict';

import mongoose from 'mongoose';


mongoose.connect('mongodb://localhost:27017/test', { useNewUrlParser: true,  useUnifiedTopology: true });

const db = mongoose.connection;

db.once('open' ,() => {
  console.log(
    'Successfully connected to the database'
  );
})

db.on('error', function(error) {
    console.error(
     'Error in MongoDb connection: ' + error
    );
    mongoose.disconnect();
});

db.on('close', function() {
    console.log(
        'Database disconnected, reconnecting to the database'
    );
});

export default db;

Create a data model (create a table)#

Create a table named StudentSchema in the test database, with name and age fields, and make it public.

import mongoose from 'mongoose';

// Create a schema
const StudentSchema = new mongoose.Schema({
    name: String,
    age: Number
})

const studentSchema = mongoose.model("StudentSchema",StudentSchema);

export default studentSchema;

Build interface routes#

Add body-parser dependency:

npm install body-parser

Import it in app.js:

import bodyParser from 'body-parser';

// Use the body-parser middleware
app.use(bodyParser.urlencoded({extended:false}));
app.use(bodyParser.json());

Create a new js file for writing data interfaces. req.body refers to the parameters in the URL, and req.params refers to the path.

import express from 'express';
import studentInfo from './studentInfo';

const router = express.Router();

router.get("/test",(req,res)=>{
    res.json({msg:"Received successfully"});
    // Example: http://localhost:3000/test
})

// Add a data
router.post('/add',(req,res) => {
    const Student = {};
    if(req.body.name){
        Student.name = req.body.name;
    }
    if(req.body.age){
        Student.age = req.body.age;
    }
    new studentInfo(Student).save().then(user => {
    res.json(user);
  });
})

// Delete a data by id
router.post('/delete',(req,res) => {
    studentInfo.remove({_id:req.body.id}).then((result)=>{
        res.json(result)
    })
})

// Get a data
router.get('/:id',(req,res) => {
    studentInfo.findOne({_id:req.params.id}).then(user => {
        if(!user) {
            return res.status(400).json("No data exists")
        }
        return res.json(user)
    }).catch(err => {
        return res.status(404).json(err)
    })
})

// Update a data
router.post('/:id',(req,res) => {
    const Student = {};
    if(req.body.name){
        Student.name = req.body.name;
    }
    if(req.body.age){
        Student.age = req.body.age;
    }
    studentInfo.updateOne({ _id: req.params.id }, { $set: Student }).then(user => {
      if (!user) {
        return res.status(400).json("Data does not exist");
      }
     res.json(user);
    })
    .catch(err => {
      return res.status(404).json(err);
    });
})

module.exports = router;

Usage#

Import it in app.js:

import test from './test';

app.use(test);

Test using Postman#

POST test:#

Set the body of the POST request to x-www-form-urlencoded, the following image is an example of the update data interface:
postman_updata.png

GET test:#

The following image is an example of getting a data by ID
postman_get.png

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.