Project address:https://github.com/jrainlau/mongoose_cru …
Write at the beginning
This article mainly shares how I use express+mongoose to add, delete, modify and check mongodb. Thank youcnodeThe help of all the excellent articles in the community and the open source project of @airuikun.airuikun/mongoose_crudThe inspiration to me.
I have been studying nodejs for less than half a month and have been thinking about what to do. Due to some PHP experience, I am interested in database operation. Taking advantage of the momentum of learning nodejs, I plan to learn mongodb as well. Mongodb gives me the feeling that it is a little more flexible than MySQL, and it is also easier to get started. Having mastered certain mongodb knowledge, he began to develop and implement the most basic functions of adding, deleting, modifying and checking.
Project preparation
First of all, you need to master certain knowledge of nodejs, express and mongodb, and have already installed express and mongoose modules, while the computer is installed with mongodb. Regarding mongodb, you can move on to another article of mine:The method of quickly starting mongodb under win7, there are 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 enterexpress -e mongoose_crud
“-e” means using ejs as the template engine (jade is too ugly to like). After the project file structure is generated, executecd mongoose_crud && npm install
Install the dependency package.
Now our project should look like this (modules folder was built by myself and will be described later):
In order to facilitate the following operations, it is recommended to usesupervisor
To start the projectnpm install supervisor -g
Enter our project folder and let’s rewrite itpackage.json
File, the inside of the “scripts” changed to the following writing
"scripts": {
"start": "supervisor ./bin/www"
},
To start the project in the future, you only need to execute it under the project folder.npm start
Just.
Rewrite file
Since the structure of the files generated by express itself is not so beautiful, it is convenient for the following work to modify them slightly.
Open first\route
Folder, delete uselessuser.js
, openindex.js
, modified to read as follows:
'use strict'
const routes = (app) => {
app.get('/', (req, res, next) => {
Res.render ('index',' title:' jrain is really handsome'})
})
}
Then open itapp.js
Folder, modified 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;
In fact, it is the route management fromapp.js
Moved to\routes\index.js
, convenient for our management.
We can test it and enter it in the browser.localhost:3000
If the output is not “Jrain is really handsome”, then there is something wrong with your project. OK, the real development will follow!
Implementation of the function of adding, deleting, modifying and checking
Under the root directory, create a new onemodules
Folder, inside a new one calledmy_class.js
In the past few days. Our project is to set up a class student management system, which can add, delete, change and check students’ names and student numbers. The document reads as follows:
'use strict'
const mongoose = require('mongoose')
//Connect 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) => {
Log ('mongodb connection succeeded! !' )
})
//Create schema
const classSchema = new mongoose.Schema({
name: String,
studentId: Number
})
//Create model
Constclassmodel = mongoose.model ('newclass', classschema)//newclass is the set created or selected.
module.exports = classModel
The effect of each paragraph can be seen in the notes. Now that we have connected the project to mongodb, we can proceed with the next steps.
We will have five pages, namely, the first page, the student information adding page, the student deleting page, the student modifying page and the student searching page. In\views
It is sufficient to establish the corresponding ejs file in the folder, and the code will not be pasted. You can go directly to the project to see:
https://github.com/jrainlau/mongoose_cru …
Then we went back\routes\index.js
, almost all our logic will be carried out here.
Change the content to the following code:
'use strict'
const classModel = require('../modules/my_class')
const routes = (app) => {
//home page
app.get('/', (req, res, next) => {
let response = res
classModel.find({}, (err, result, res) => {
if(err) return console.log(err)
response.render('index', { result })
})
})
//Increase 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("<a href='/' > Add Successfully, Click to Return to Home < /a > ")
})
})
//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("<a href='/' > delete succeeded, click back to home < /a > ")
})
})
//Modify 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('<script>alert ("please check the students to be modified") < /script >')
}
Res.send("<a href='/' > modified successfully, click back to home < /a > ")
})
})
//Find Students
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
The principle is that the program receives parameters through post request and performs corresponding operations to realize the function of adding, deleting, modifying and checking. The main API used are as follows:
-
.find()
For reading and searching student information. -
.create()
For increasing student information. It is based on the operation of model in mongoose, passing in a json object as the content to be added, which can be consulted by itself. -
.update()
For updating student information. -
.remove()
For deleting student information.
Our project has been completed, let’s test it!
The end
This article is not a tutorial, but only a record of my study. If it can be useful to others, it is best. If you think I am wrong, please correct me. Thank you all ~!