The Node learning – 05 – mongo
Install the mongo
-
Download: www.mongodb.com/download-ce…
-
For details about how to install environment variables, see “Newbie”
-
Validation:
mongod -version
Copy the code
Enable and disable the MongoDB database
-
Ensure that the data/ DB folder exists in the root directory of the disk where the installation directory resides.
-
Enter mongod in CMD to start the database
-
Example Modify a data store directory
Mongod --dbpath= Data store directory pathCopy the code
-
Stop: CTRL + C or close CMD directly
Basic Perception of MongoDB
Connecting to a Database
// Connect to the local MongoDB service mongo by defaultCopy the code
exit
exit
Copy the code
Basic commands
-
Show all databases
show dbs Copy the code
-
View the database for the current operation
db Copy the code
-
Creating a database
Use database name (if not, it will be created)Copy the code
-
Insert data
db.students.insertOne({"name": "xxx"}); Copy the code
-
View all data
db.students.find(); Copy the code
Manipulate MongoDB data in Node
mongoose
Use third-party Mongoose to operate the MongoDB database
The installation
npm install --save mongodb
Copy the code
Use the demo
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
const Cat = mongoose.model('Cat', { name: String });
// const kitty = new Cat({ name: 'Zildjian' });
// kitty.save().then(() => console.log('meow'));
for (var i = 0; i< 100; i++) {
var kitty = new Cat({name: 'meow meow' + i});
kitty.save().then(() = > {
console.log('meow'); })}Copy the code
The basic concept
- Database, which can have multiple databases
- Data table -> collection, which is simply an array
- The document
{
/ / database
qq: {
/ / collection
users: [
/ / documentation
{id: 1, name: 'aaa'},
{id: 2, name" 'bbb'} ], products: [] }, taobao: { }, baidu: { } }Copy the code
CRUD basic usage
/ / introduction
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
// Connect to the database
// localhost ITcast database
// If the itcast database does not exist, it will be created automatically after the first database is inserted
mongoose.connect('mongodb://localhost/itcast');
// Design a collection structure/table structure
// Field names are the names of attributes in the table structure
const userSchema = new Schema({
username: {
type: String.required: true
},
password: {
type: String.required: true
},
email: {
type: String}});Publish the document structure as a model
// The mongoose. Model method is used to publish an architecture as a model
// The first argument: pass in an uppercase singular string to represent the database name, which Mongoose will automatically pass in
// The string of uppercase nouns generates the lowercase plural collective noun User -> users
// The second parameter, Schema
// Return value: model constructor
const User = mongoose.model('User', userSchema);
// Once you have the model construct data, you can use this constructor to add, delete, modify, and query the data in the user collection
// Add data
const admin = new User({
username: 'admin'.password: '123456'.email: '[email protected]'
});
admin.save().then((res) = > {
console.log(res);
console.log('Saved successfully');
});
// Query data
// 1. Query all information
console.log('---------- query all -------------------');
User.find().then(res= > console.log(res));
// Query by condition, return an array
console.log('---------- by condition -------------------');
User.find({ username: 'ZS' }).then(res= > console.log(res));
// Only one object is returned
console.log('---------- query only one -------------------');
User.findOne({ username: 'ZS' }).then(res= > console.log(res));
// Delete data
User.deleteMany({ username: 'ZS' }).then(res= > console.log(res));
// Update data
User.findByIdAndUpdate("61061a42c988a30d10ec8e1d", { password: '123' })
.then(res= > console.log(res));
Copy the code
CRUD case rewritten by Mongoose
students.js
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/students', { useUnifiedTopology: true }, { useNewUrlParser: true });
const Schema = mongoose.Schema;
const studentSchema = new Schema({
name: {
type: String.required: true
},
gender: {
type: String.enum: ['0'.'1'].required: true
},
age: {
type: Number
},
hobbies: {
type: String}});module.exports = mongoose.model('Student', studentSchema);
Copy the code
router.js
const fs = require('fs');
const Student = require('./students.js');
const express = require('express');
1. Create a routing container
const router = express.Router();
// 2. Mount all routes to the route container
/ / the main interface
router.get('/students'.function (req, res) {
Student.find(function (err, data) {
if (err) {
return res.status(500).send('Server error');
}
res.render('index.html', {
students: data
})
})
})
// Add a page
router.get('/students/new'.function (req, res) {
res.render('new.html');
})
// Click add
router.post('/students/new'.function (req, res) {
const student = new Student(req.body);
student.save(function (err, data) {
if (err) {
return res.status(500).send('Server error');
}
res.redirect('/students');
});
})
// Edit the page
router.get('/students/edit'.function (req, res) {
Student.findById(req.query.id, function (err, data) {
if (err) {
return res.status(500).send('Server error');
}
res.render('edit.html', {
student: data
})
})
})
// Click edit
router.post('/students/edit'.function (req, res) {
const id = req.body.id;
Student.findByIdAndUpdate(id, req.body, function (err, data) {
if (err) {
return res.status(500).send('Server error');
}
res.redirect('/students'); })})// Click delete
router.get('/students/delete'.function (req, res) {
Student.findByIdAndRemove(req.query.id, function(err, data) {
if (err) {
return res.status(500).send('Server error');
}
res.redirect('/students');
});
})
module.exports = router;
Copy the code