Recently, as the start of the school year approaches, there are more and more things to do, such as stargazing, physical education classes, and school courses... Everything is gradually falling into place, except for my learning path, which is still off track. I often stop and don't know what to study, and I can't find the motivation to learn. I worry that what I learn will be useless and that I will give up halfway. It's no wonder they say that the beginning of everything is difficult. But once I start taking action and get busy, I feel fulfilled. As long as I take action, no matter the result, it's always better than not trying at all. "Do good deeds without asking about the future." I have also struggled with whether to learn node.js or Java to operate the backend database. Some people say to learn node.js because front-end engineers should know it; others say to learn Java and study SSM and the entire Spring framework; and some say that node.js has no future. Finally, I saw an answer online. "He said: Programmers should not be constrained by language, let alone frameworks. Use the right tool for the right scenario." The so-called lack of future is always the result of using the right tool incorrectly. You have to have the heart to build a spaceship with C++. 🚀
What is node.js?#
According to the official description:
Node.js® is a JavaScript runtime built on Chrome’s V8 JavaScript engine.
Node.js is an environment that can execute JavaScript, and V8 is the JavaScript engine of the mainstream browser - Google Chrome, responsible for executing JavaScript. Node.js, along with a series of C/C++ packages, allows our server-side to also execute JavaScript.
Environment Installation#
Node.js installation#
Download link: Node.js Official Website Download
MongoDB database#
Download link: MongoDB Official Website Download
Start the service
In the MongoDB folder, use the command line to enter .\mongo to start the service.
Visualization tool Robo3T#
Used for visual operation of MongoDB database, download link: Robo3T
express#
Express is a concise and flexible node.js web application framework that provides a series of powerful features to help you create various web applications and rich HTTP tools.
Express scaffolding#
Express scaffolding installation:
npm install -g express-generator
Create an express project:
express test
cd test
npm install
Run:
npm start
Browser access:
Introducing babel into express scaffolding#
Introducing babel is to transpile ECMAScript 2015+ to a version compatible with browsers, in other words, to allow us to use ES6.
Dependencies
Remember to execute npm install to update dependencies after modification.
{
"name": "test",
"version": "0.0.0",
"private": true,
"scripts": {
"start": "node ./index.js",
"devstart": "nodemon ./index.js"
},
"dependencies": {
"babel": "^6.23.0",
"babel-cli": "^6.24.1",
"babel-core": "^6.24.0",
"babel-preset-es2015": "^6.24.0",
"babel-preset-stage-3": "^6.22.0",
"babel-register": "^6.24.0",
"cookie-parser": "~1.4.4",
"debug": "~2.6.9",
"express": "~4.16.1",
"http-errors": "~1.6.3",
"jade": "~1.11.0",
"mongoose": "^5.10.5",
"morgan": "~1.9.1"
},
"devDependencies": {
"babel-plugin-transform-async-to-generator": "^6.24.1",
"babel-plugin-transform-es2015-classes": "^6.24.1",
"babel-plugin-transform-es2015-modules-commonjs": "^6.24.1",
"babel-plugin-transform-export-extensions": "^6.22.0"
}
}
Create .babelrc in the root directory
The file code is as follows:
{
"presets": ["stage-3"],
"plugins": [
"transform-async-to-generator",
"transform-es2015-modules-commonjs",
"transform-export-extensions"
]
}
Create index.js in the root directory
The file code is as follows:
require('babel-core/register');
require('./bin/www');
At this point, syntax support for import and other ES6 syntax is available.
Node.js operation of MongoDB database#
Dependencies#
Install Mongoose in the project root directory
npm install mongoose --save
Connect to the database#
Use mongoose to connect to MongoDB. Create a db.js file in the project:
'use strict';
import mongoose from 'mongoose';
mongoose.connect('mongodb://localhost:27017/test', { useNewUrlParser: true });
const db = mongoose.connection;
db.once('open' ,() => {
console.log(
'Database connection successful'
);
})
db.on('error', function(error) {
console.error(
'Error in MongoDb connection: ' + error
);
mongoose.disconnect();
});
db.on('close', function() {
console.log(
'Database disconnected, reconnecting to the database'
);
});
export default db;
Then import it in app.js
import db from './mongodb/db';
At this time, running the project will create a test database in MongoDB, but it will not be displayed because there is no data in it.
Add data#
// Import modules
import mongoose from 'mongoose';
import db from './mongodb/db';
// Create schema
// Schema is a collection in MongoDB, or a table in the database
let testSchema = new mongoose.Schema({
name: String,
age: Number
})
// Create model through connection and schema
let testModel = connection.model('test1', testSchema);
// Create document by instantiating model
let test = new testModel({
name: 'Magren',
age: 20
})
// Insert the document into the database, the save method returns a Promise object.
test.save().then((doc) => {
console.log(doc)
})
After successful addition, a table named test1 will be added to the MongoDB database, and a data with name Magren and age 20 will be added to the table.
Read data#
// Import modules
import mongoose from 'mongoose';
import db from './mongodb/db';
let testSchema = new mongoose.Schema({
name: String,
age: Number
})
let testModel = connection.model('test1', testSchema);
// Query condition, query records with name Magren, format is key-value pair
// When the query condition is empty, it means querying all data in the table
testModel.find({name: 'Magren'}).then(doc => {
console.log(doc);
})
To reuse code and reduce coupling, the Schema and Model module codes are generally separated.
Update data#
// Import modules
import mongoose from 'mongoose';
import db from './mongodb/db';
let testSchema = new mongoose.Schema({
name: String,
age: Number
})
let testModel = connection.model('test1', testSchema);
// The first parameter is the query condition, find the data with name Magren
// The second parameter is the value to be modified
testModel.updateMany({name: 'Magren'},{age: 18}).then((result)=>{
console.log(result)
})
Delete data#
// Import modules
import mongoose from 'mongoose';
import db from './mongodb/db';
let testSchema = new mongoose.Schema({
name: String,
age: Number
})
let testModel = connection.model('test1', testSchema);
// Delete the data with name Magren
testModel.removeMany({name: 'Magren'}).then((result)=>{
console.log(result)
})
Finally#
Now I have only learned the basic operation of node.js on the MongoDB database. I will try to do a small project and deploy it on the server someday. I feel like I will encounter many problems again... But if there is no practice, it is just empty talk. Let's accelerate our learning. After all, I am already a junior. ✊