当前位置:网站首页>Use nodejs+express+mongodb to complete the data persistence project (with modified source code)
Use nodejs+express+mongodb to complete the data persistence project (with modified source code)
2022-07-03 20:24:00 【Brave * Niuniu】
utilize nodejs+express+mongodb Complete the data persistence project
Additions and deletions

- Available console view mongodb Whether the database data is successfully stored

A problem encountered , Back to id Attribute values are quoted . Special attention 
Using mongodb Before database storage , Remember to open the database , Then connect to the database 
student.js Core code :
var mongoose = require('mongoose');
mongoose.connect('mongodb://127.0.0.1/test');
var Schema = mongoose.Schema;
var studentSchema = new Schema({
name: {
type: String,
required: true
},
sex: {
type: Number,
// Enumerate these numbers
enum: [0, 1],
default: 1
},
age: {
type: Number
},
hover: {
type: String
}
})
// Export the model constructor directly
module.exports = mongoose.model('Student', studentSchema)
router.js Modify the core code
// Routing module design set
var fs = require('fs');
var path = require('path');
var Student = require('./student');
/* Student.updataByid({ id: 1, name: " Li Si ", age: 19 }, function (err) { if (err) { return console.log(' Modification failed '); } console.log(' Modification successful '); }) */
var express = require('express');
// Create a routing container
var router = express.Router();
// Mount the router to router In the container
router.get('/students', function (req, res) {
// Parameter 2 is optional , hold uft8 Characters are converted into strings we know
/* fs.readFile(path.join(__dirname, './db.json'), 'utf8', function (err, data) { if (err) { // Status code 500, Server error console.log(" Something went wrong "); // return res.status(500).send('Server error.'); } res.render('index.html', { // The data read from the file must be a string // So we must turn it into an object students: JSON.parse(data).student }); }) */
Student.find(function (err, students) {
if (err) {
return res.status(500).send('Server error.');
}
res.render('index.html', {
students: students
});
})
})
router.get('/students/new', function (req, res) {
res.render('new.html');
})
router.post('/students/new', function (req, res) {
/* 1. Get form data 2. Handle ( Save the data in db.json Achieve persistence ) 3. Send a response */
// console.log(req.body);
// Read it out first , Turn to object
// Then go to the object push data , Then turn the object into a string
// Then write the string to the file again
var student = req.body;
new Student(student).save(function (err) {
if (err) {
return res.status(500).send('Server error.');
}
res.redirect('/students');
})
})
router.get('/students/edit', function (req, res) {
// Handle connection problems in the list of clients ( Need to have id Parameters )
// Get the students to edit
// Render edit page "1. according to id Find out the student information , Then the template engine renders the page
// console.log(req.query.id); Can get id
// Turn the obtained string into Wie Without quotation marks id data
// Regular expression patterns
Student.findById(req.query.id.replace(/"/g, ''), function (err, student) {
if (err) {
return res.status(500).send('Server error.');
}
// see ID Student :console.log(student);
res.render('edit.html', {
student: student
})
})
})
router.post('/students/edit', function (req, res) {
// Get form data
// to update
// Struend.updataId()
// console.log(req.body);
var id = req.body.id.replace(/"/g, '')
Student.findByIdAndUpdate(id, req.body, function (err) {
if (err) {
return res.status(500).send('Server error.');
}
})
res.redirect('/students')
})
router.get('/students/delete', function (req, res) {
// 1. Get the id
// 2、 according to id Delete
// 3. Send the response data according to the operation result
// console.log(req.query.id);
var id = req.query.id.replace(/"/g, '')
Student.findByIdAndRemove(Aid, function (err) {
if (err) {
return res.status(500).send('Server error.');
}
res.redirect('/students')
})
})
// hold router export
module.exports = router;
边栏推荐
- [effective Objective-C] - block and grand central distribution
- LabVIEW training
- In 2021, the global foam protection packaging revenue was about $5286.7 million, and it is expected to reach $6615 million in 2028
- In 2021, the global revenue of syphilis rapid detection kits was about US $608.1 million, and it is expected to reach US $712.9 million in 2028
- Titles can only be retrieved in PHP via curl - header only retrieval in PHP via curl
- Sword finger offer 30 Stack containing min function
- Rd file name conflict when extending a S4 method of some other package
- 2166. Design bit set
- Global and Chinese markets of lithium chloride 2022-2028: Research Report on technology, participants, trends, market size and share
- App compliance
猜你喜欢

Kubernetes cluster builds efk log collection platform

The global industrial design revenue in 2021 was about $44360 million, and it is expected to reach $62720 million in 2028. From 2022 to 2028, the CAGR was 5.5%

Preliminary practice of niuke.com (11)

String and+

In 2021, the global foam protection packaging revenue was about $5286.7 million, and it is expected to reach $6615 million in 2028

Don't be afraid of no foundation. Zero foundation doesn't need any technology to reinstall the computer system

It is discussed that the success of Vit lies not in attention. Shiftvit uses the precision of swing transformer to outperform the speed of RESNET

Virtual machine installation deepin system

2022 Xinjiang latest construction eight members (standard members) simulated examination questions and answers

Based on laravel 5.5\5.6\5 X solution to the failure of installing laravel ide helper
随机推荐
Fingerprint password lock based on Hal Library
Point cloud data denoising
6006. Take out the minimum number of magic beans
Nerfplusplus parameter format sorting
Global and Chinese markets of lithium chloride 2022-2028: Research Report on technology, participants, trends, market size and share
你真的知道自己多大了吗?
Test changes in Devops mode -- learning and thinking
Don't be afraid of no foundation. Zero foundation doesn't need any technology to reinstall the computer system
Instructions for common methods of regular expressions
About callback function and hook function
Basic knowledge of dictionaries and collections
Teach you how to quickly recover data by deleting recycle bin files by mistake
Global and Chinese market of speed limiter 2022-2028: Research Report on technology, participants, trends, market size and share
[postgresql]postgresql custom function returns an instance of table type
Use of aggregate functions
Upgrade PIP and install Libraries
2022 Xinjiang latest construction eight members (standard members) simulated examination questions and answers
1.4 learn more about functions
Global and Chinese market of cyanuric acid 2022-2028: Research Report on technology, participants, trends, market size and share
Shortest path problem of graph theory (acwing template)