Recently, there have been more and more things to do since the start of school, including stargazing, health 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 learn, and I can't find the motivation to study. 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 what the result is, it's always better than not trying at all.
Do good deeds without asking about the future
I have also struggled with whether to use Node.js or Java to operate the backend database.
Some people say to learn Node.js because front-end engineers should know it; some say to learn Java and the SSM framework; and some say that Node.js has no future.
Finally, I came across an answer online,
he said: programmers should not be constrained by languages or frameworks. Use the right tool for the right job.
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, successfully allows our server-side to execute JavaScript.
Installation#
Node.js Installation#
Download link: Node.js Official Website
MongoDB Database#
Download link: MongoDB Official Website
Starting the Service
In the MongoDB folder, use the command line in the bin directory to enter: .\mongo to start the service.
Visualization Tool - Robo3T#
Used for visual operations on the MongoDB database, download link: Robo3T
Express#
Express is a concise and flexible node.js web application framework that provides a range of powerful features to help you create various web applications and rich HTTP tools.
Express Scaffold#
Express scaffold installation:
npm install -g express-generator
Create an Express project:
express test
cd test
npm install
Run:
npm start
Access in the browser:
Introducing Babel to the Express Scaffold#
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 after modification to update the dependency packages.
{
"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, the syntax supports import and other ES6 syntax.
Node.js Operations on 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 point, 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
// A schema is a collection in MongoDB, or a table in a database
let testSchema = new mongoose.Schema({
name: String,
age: Number
})
// Create a model using connection and schema
let testModel = connection.model('test1', testSchema);
// Create a document by instantiating the 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, the MongoDB database will have a new table called test1, and the table will have a new record with name as Magren and age as 20.
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 as Magren, in the format of key-value pairs
// 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, it is generally a good practice to separate the Schema and Model modules.
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 as 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 as Magren
testModel.removeMany({name: 'Magren'}).then((result)=>{
console.log(result)
})
Finally#
Now I have only learned the basic operations 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 challenges...
But without practice, it's just empty talk. Let's accelerate our learning. After all, I'm already a junior. ✊