"node. js" II, based on Express framework + Connect MongoDB + Write back-end interface

Source: Internet
Author: User
Tags data structures






In the previous section, we talked about how to build an express environment, and now we're talking about how to write a service interface to a front-end call through node. js












1. First build database and tables through MongoDB






For example, my database name is Db_demo and the database table is goods






The data structures in table goods are as follows:




‘ProductId’: {type: String}, // product id

‘ProductName’: String, // product name

‘SalePrice’: Number, // commodity price

‘ProductImage’: String // product image



2. Install Mongoose to drive and operate MongoDB


npm install mongoose





3. Under the server folder, create a new folder, models, which creates a js file about the commodity interface. The file structure is as follows:



The contents of goods.js are as follows:


var mongoose = require (‘mongoose’)

var Schema = mongoose.Schema


var productSchema = new Schema ({

 ‘ProductId’: {type: String},

 ‘ProductName’: String,

 ‘SalePrice’: Number,

 ‘ProductImage’: String

})


module.exports = mongoose.model (‘Good‘, productSchema)





4. Under the / routes / folder, create a new js file goods.js that specifically writes backend interface logic.


var express = require (‘express’)

var router = express.Router ()

var mongoose = require (‘mongoose’)

var Goods = require (‘../ models / goods’)

// Connect to MongoDB database

mongoose.connect (‘mongodb: //127.0.0.1: 27017 / db_demo’)


mongoose.connection.on (‘connected’, () => {

 console.log (‘MongoDB connected success.’)

})


mongoose.connection.on (‘error‘, () => {

 console.log (‘MongoDB connected fail.’)

})


mongoose.connection.on (‘disconnected’, () => {

 console.log (‘MongoDB connected disconnected.’)

})


// Query product list data

router.get ("/", (req, res, next) => {

 // Accept the parameters from the front end

 let page = parseInt (req.param (‘page‘))

 let pageSize = parseInt (req.param (‘pageSize’))

 let sort = req.param ("sort")

 let skip = (page-1) * pageSize

 let params = {};

 let goodsModel = Goods.find (params) .skip (skip) .limit (pageSize)

 goodsModel.sort ({‘salePrice‘: sort})

 goodsModel.exec ((err, doc) => {

   if (err) {

     res.json ({

       status: ‘1‘,

       msg: err.message

     })

   } else {

     res.json ({

       status: ‘0’,

       msg: ‘‘,

       result: {

         count: doc.length,

         list: doc

       }

     })

   }

 })

})


module.exports = router;





5. Finally, configure the routing address access / router / goods.js interface in app.js







6. Open the browser, the effect is as follows:







Successfully call the background interface, the background interface calls the MongoDB database, and finally returns the json data!






--end--






[Node.js] Second, based on the Express framework + connect MongoDB + write back-end interface




Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.