Written in 2016.04.05
Project address: github.com/jrainlau/mo…
Written in the beginning
This article mainly shares how I used Express + Mongoose to implement the add, delete, change and check operation of mongodb. Thanks for the help of all the high-quality articles in cNode community and the inspiration of @airuikun’s open source project Airuikun/Mongoose_crud. I’ve been learning NodeJS for less than half a month now, trying to figure out what to do. As I have some PHP experience, I am interested in the operation of database. With the momentum of learning NodeJS, I decided to learn mongodb as well. Mongodb gives me the feeling that it will be a little more flexible than MySQL and easier to use. After mastering certain mongodb knowledge, we began to develop and realize the most basic function of add, delete, change and check.
Project preparation
First of all, you need to have some knowledge of NodeJS, Express and mongodb, and have installed express and Mongoose modules, and mongodb is installed on your computer. For mongodb questions, you can go to my other article: win7 quick start mongodb method, which has detailed installation and configuration process. At the same time, it is recommended to use Robomongo as the visual operation tool of mongodb, which is convenient for us to directly view and operate the database.
Project start
Open the command line and type express-e mongoose_crud “-e” to use EJS as the template engine (Jade is too ugly to like). After generating the project file structure, run CD mongoose_crud && NPM install to install the dependencies. Now our project should look like this (the Modules folder is something I built myself, which I’ll cover later) :
To facilitate the following operations, it is recommended that we use Supervisor to start the project NPM install Supervisor -g to enter our project folder. Let’s rewrite the package.json file and change the “scripts” in it to read as follows
"scripts": {
"start": "supervisor ./bin/www"
},
Copy the code
To start the project, simply run NPM start in the project folder.
Rewrite the file
Since the file structure generated by Express itself is not as elegant, it is slightly modified for the rest of the work. First open the \route folder, delete the unused user.js, open index.js, and change it to the following:
'use strict'
const routes = (app) => {
app.get('/', (req, res, next) => {
res.render('index', { title: 'Jrain is really handsome '})})}Copy the code
Then open the app.js folder and change it to the following:
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var routes = require('./routes/index');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine'.'ejs');
// uncomment after placing your favicon in /public
app.use(favicon(path.join(__dirname, 'public'.'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
routes(app)
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') = = ='development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
Copy the code
In fact, the route management has been moved from app.js to \routes\index.js for our convenience. We can test it by typing localhost:3000 in the browser and if it doesn’t say “Jrain is really cool” then there is something wrong with your project. OK, now for the real development!
Add, delete, change and check function
In the root directory, create a new modules folder with a new file called my_class.js. Our project is to establish a class student management system, which can add, delete, change and check the names and student numbers of students. The content of the document is as follows:
'use strict'
const mongoose = require('mongoose'// Connect to mongodb mongoose. Connect ('mongodb://localhost/test'// instantiate the connection object const db = mongoose. Connection db.on('error', console.error.bind(console, 'Connection error:'))
db.once('open', (callback) => {
console.log('MongoDB connection successful!! '}) // Create schema const classSchema = new mongoose.Schema({name: String, studentId: studentId) // create model const classModel = mongoose. Model ('newClass', classSchema) // newClass for the created or selected collection module.exports = classModelCopy the code
The function of each paragraph can be seen in the notes. Now that we have the project connected to mongodb, we can proceed with the next steps. We will have five pages, namely the home page, student information increase page, student delete page, student modify page, student search page. In \views folder to create the corresponding EJS file, the code is not posted, you can directly go to the project to see: github.com/jrainlau/mo… Then we go back to \routes\index.js, where almost all of our logic will be done. Change this to the following code:
'use strict'
const classModel = require('.. /modules/my_class') const routes = (app) => {//'/', (req, res, next) => {
let response = res
classModel.find({}, (err, result, res) => {
if(err) return console.log(err)
response.render('index', {result})}) // Add student information app.get('/create', (req, res, next) => {
res.render('create', {})
})
app.post('/create', (req, res, next) => {
let newStudent = [{
name: req.body.name,
studentId: req.body.student_id
}]
classModel.create(newStudent, (err) => {
if(err) return console.log(err)
res.send(})}) // Delete student information app.get('/del', (req, res, next) => {
let response = res
classModel.find({}, (err, result, res) => {
if(err) return console.log(err)
response.render('del', { result })
})
})
app.post('/del', (req, res, next) => {
classModel.remove({_id: req.body.student}, (err, result) => {
if(err) return console.log(err)
console.log(result.result)
res.send(})}) // Change student information app.get('/update', (req, res, next) => {
let response = res
classModel.find({}, (err, result, res) => {
if(err) return console.log(err)
response.render('update', { result })
})
})
app.post('/update', (req, res, next) => {
console.log(req.body)
let num = req.body.num,
condiction = {_id: req.body._id[num]},
query = {$set: {name: req.body.name[num], studentId: req.body.student_id[num]}}
classModel.update(condiction, query, (err, result) => {
if(err) {
console.log(err)
res.send('')
}
res.send(})}) // Find student app.get('/reach', (req, res, next) => {
let result = null
res.render('reach', { result })
})
app.post('/reach', (req, res, next) => {
console.log(req.body)
let response = res
let reachType = req.body.reach_type,
keyWord = req.body.keyword
if (reachType == 0) {
classModel.find({name: keyWord}, (err, result) => {
if(err) return console.log(err)
response.render('reach', { result })
})
} else {
classModel.find({studentId: keyWord}, (err, result) => {
if(err) return console.log(err)
response.render('reach', { result })
})
}
})
}
module.exports = routes
Copy the code
Its principle is that the program receives parameters through POST request, carries on the corresponding operation, realizes the increase, deletion, change and check function. The main apis used are as follows:
.find()
To read and find student information..create()
To increase student information. It is based on the operation of Model in Mongoose, and a JSON object is passed in as the content to be added. You can refer to the details by yourself..update()
To update student information..remove()
To delete student information.
Our project is complete, let’s test it!
The end of the
This article is not a tutorial, just a record of my own learning. It would be great if it could be useful to others, and I’m welcome to correct you if you think I’m wrong. Thank you all ~!