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