Use Njs+ Express +mongoDB to create a simple server
preface
This article mainly introduces how to use NJs+ Express +mongoDB to create a simple server, which can be based on the development of the project server.
1. Prepare
- Install express
npm install express
Copy the code
- Install Mongoose (for connecting to monogoDB database)
npm install mongoose
Copy the code
- File directory structure
2. Connect to the mongoDB database and create a data model
models/user.js
//1. Const mongoose = require('mongoose'); //2. Open const db = if there is authentication Mongoose. The createConnection (' mongo: / / user name: password @ localhost: 27017 / database name ', {useNewUrlParse: true, useUnifiedTopology: True}, err = > {the if (err) {the console. The log (" -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- ") the console. The log (" database connection fails, "err) The console. The log (" -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- ") return} the console. The log (" database connection success ")}) / / 3. Set the data model (declare which collection it is, //mongoose. Model ('name',schema) const model = db.model('user', {uname:{type:String,default:" one, two, three, four "}, pwd:String, email:String, sex:String }); // Add new user method const createModel = postData =>{const insertObj = new model(postData) return insertobj.save (). Then (res =>{ Console. log(res) // db.close() return res}). Catch (err => {console.log(' failed to insert '+ err) return false})} const findModel = (skip = 0,limit = 0)=>{ if (! Skip) {skip = 0} Default: 0 return model.find().skip(skip).limit(limit).then(res=>{return res}).catch(err=>{console.log(' query failed '+ err) Module.exports = {createModel, findModel} // exports = {createModel, findModel}Copy the code
3. Define the method of creating data through the model
controller/user.js
Const {createModel,findModel} = require(process.cwd() + '/models/user') const create = async(req,res)=>{ / / 1. Let postData = req.query //2 Filter (ignore console.log(postData) //3. Let rs = await createModel(postData) //4 If (rs) {res.send({meta:{state:200, MSG :" add successful ", data:postData})} else {res.send({meta:{state:500, data:postData})} else {res.send({meta:{state:500, data:postData})} }} const find = async (req,res)=>{//1 accept data let pageInfo = req.query //2 Let skip = (parseInt(pageinfo.pageno) -1) * parseInt(pageinfo.pagesize) console.log(pageInfo) let rs = await findModel(skip,parseInt(pageInfo.pagesize)) // let rs = await findModel() if (rs) { res.send({ meta:{ state:200, MSG :" query failed "}, data:rs})} else {res.send({meta:{state:500, MSG :" query failed "}, Data :rs})}} // Export member module.exports = {create, find}Copy the code
4. Create an import file
http.js
Const express = require('express') // 2 CreateServer const app = new Express () // 3 Route, syntax app.HTTP request mode (path, App.get ('/',(req,res)=>{res.send(' Hello Express ')}) const userController = Require (process.cwd()+'/controller/user') // student add app.post('/user',userController.create) // student list query app.get('/user',userController.find) // 4. Listen (3000,()=>{console.log('http://localhost:3000')})Copy the code
5. Run the node/ Nodemon server
nodemon http.js
Copy the code
That’s when you can get throughhttp://127.0.0.1:3000 visit the server!
Order one if you likeHas (ˆ ◡ ˆ ԅ)