preface
The advent of Node.js makes it possible to develop back end services using front-end syntax (javascript), and more and more front ends are moving to the back end and even the full stack. Back-end development involves database operations. MongoDB is an open source database system based on distributed file storage. This article describes how to play MongoDB with Node.js + Mongoose. I hope I can help someone in need.
Since I develop on a Mac, all of the following operations are done under a Mac.
First, environment construction
Installation Node. Js
The node environment can be skipped.
The Nodejs website provides the macOS installation package. You can download and install it directly. Now NodeJS is stable at 12.11.1.
Install the mongo
MongoDB is a document-based, general-purpose distributed database built for modern application developers and the cloud era.
Last month (September) macOS package manager Homebrew announced the removal of MongoDB. The reason is that last October MongoDB announced that it would switch its open source License from GNU AGPLv3 to SSPL (Server Side Public License), In response to cloud vendors like AWS offering MongoDB as a service to users without giving back to the community, MongoDB hopes to generate revenue from software-as-a-service. Homebrew believes MongoDB is no longer open source…
Anyway, due to the above reasons, we cannot directly install mongodb using brew Install mongodb. Fortunately, MongoDB maintains a custom Homebrew tap of its own. The installation steps were updated in Install MongoDB Community Edition.
The latest steps for installing MongoDB on Mac are as follows:
1. Install firstHomebrew
Homebrew is the package manager for macOS. Because OSX does not include the Homebrew brew package by default, install it first and skip those that have already been installed.
/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
Copy the code
The installation process is a bit long, and the terminal output is more than one screen, so I’ve only captured the first and last parts.
2. Then get the MongoDB Homebrew Tap
brew tap mongodb/brew
Copy the code
3. Install MongoDB CE (Community Edition)
The brew install [email protected]Copy the code
Now you have the MongoDB environment installed on your Mac.
Install the mongoose
Node.js can directly operate MongoDB, but it is tedious to directly write MongoDB validation, data type conversion and business logic template through MongoDB command syntax. So we used mongoose.
Mongoose is an object model tool for MongoDB. It encapsulates the common methods of MongoDB and makes node.js operation of MongoDB more elegant and concise.
While node.js and MongoDB are installed globally, mongoose is installed in your project:
cd your-project
npm i -S mongoose
Copy the code
Your development environment is now fully installed.
Start the MongoDB service
To operate MongoDB, first start it. There are two ways to start the MongoDB service:
1. Run in the foreground
mongod --config /usr/local/etc/mongod.conf
Copy the code
The benefit of running in the foreground is that you can see some feedback and logs for debugging purposes. In addition, to disable the service, just press the Control + C key on the terminal.
2. It can also run as a macOS service in the background
The brew services start [email protected]Copy the code
The advantage is that the startup automatically, can be used at any time.
stop
Services stop [email protected] brewCopy the code
Your MongoDB database is now open.
3. Operate MongoDB
Before we do that, let’s explain some of the core concepts in MongoDB and Mongoose.
MongoDB
- Data logging in MongoDB is one
BSON
(BSON is a JSON file format described in binary). - Mongo will
file
Stored in theA collection of
,A collection of
Stored in theThe database
In the. - MongoDB databases and collections do not need to be created manually.
A collection of the collection
: is equivalent to the relational databaseTable table
.File the document
: Data recording unit of MongoDB, equivalent to relational databaseRecord the row
.
mongoose
schema
In Mongoose, everything comes from oneschema
, eachschema
Mapped to a MongoDBA collection of
It defines thisA collection of
In theThe document
The skeleton.model
A:file
By compilingschema
I get onemodel
Is an example offile
.model
Responsible for creating and reading from the MongoDB databaseThe document
.
More mongoose concepts can be found in the Mongoose Guide.
Database operations:
1. Connect MongoDB with Mongoose
Create the connection.js file in your project
// connection.js file
const mongoose = require('mongoose'); Const conn = mongoose. The createConnection (/ / connection address, mongo's service port 27017 / / dbtest is I want to use the database name, when writing data to their products, MongoDB automatically creates a database called dbTest instead of creating it manually.'mongo: / / 127.0.0.1:27017 / dbtest'// Some compatible configuration, must be added, you do not write run time prompt you to add. { useNewUrlParser:true,
useUnifiedTopology: true
}
)
conn.on('open', () => {
console.log('Open mongodb connection');
})
conn.on('err', (err) => {
console.log('err:' + err);
})
Copy the code
Run:
node conection.js
Copy the code
You can see that “Open mongodb connection” is printed and the run is waiting.
This means that you are now successfully connected to MongoDB and ready to start working with the database.
To make extensions easier, let’s first modify connection.js to export it as a module so that it can be imported and reused elsewhere.
// connection.js file
const mongoose = require('mongoose');
const conn = mongoose.createConnection(
'mongo: / / 127.0.0.1:27017 / dbtest',
{
useNewUrlParser: true,
useUnifiedTopology: true
}
)
conn.on('open', () => {
console.log('Open mongodb connection');
})
conn.on('err', (err) => {
console.log('err:'+ err); }) module.exports = conn; //commonJs syntax to export the CONN module.Copy the code
2. Add operations
The save | the create method
Create an insert. Js file
// insert.js file
let mongoose = require('mongoose'); // Import the connection modulelet connection = require('./connection'); / / create a schemaletStudentSchema = new mongoose.Schema({name: String, age: Number}) // Use connection and Schema to create a modellet StudentModel = connection.model('Student', StudentSchema); // Create the document by instantiating the modellet studentDoc = new StudentModel({
name: 'zhangsan', age: 20}) // Insert the document into the database, and the save method returns a Promise object. studentDoc.save().then((doc) => { console.log(doc) })Copy the code
Run:
node insert.js
Copy the code
To see the results of operating the database more directly, it is recommended that you install a database visualization tool: Robo3T, download the MAC version of the installation.
After clicking on the upper left corner of Robo3T to connect to our database, you can see that MongoDB automatically generates the database and collection for us, and a record has been inserted:
Or you can insert the data directly through the Model’s create method, which also returns a Promise:
StudentModel.create({
name: 'lisi',
age: 19
}).then((doc) => {
console.log(doc)
})
Copy the code
3. Read operations
The find method
In order to reuse code properly, let’s separate the StudentSchema and StudentModel:
Create the studentSchema.js file
// StudentSchema.js file
const mongoose = require('mongoose');
let StudentSchema = mongoose.Schema({
name: String,
age: Number
})
module.exports = StudentSchema;
Copy the code
Create the studentModel.js file
// StudentModel.js file
const connection = require('./connection');
const StudentSchema = require('./StudentSchema');
let StudentModel = connection.model('Student', StudentSchema);
module.exports = StudentModel;
Copy the code
Then create a new query.js file
// query.js file
const StudentModel = require('./StudentModel'); / / rich query conditions, object format, key/value pair, for query name for the record of lisi StudentModel. Below find ({name:'lisi'}).then(doc => {
console.log(doc);
})
Copy the code
run
node query.js
Copy the code
You can see that the record with name lisi is printed.
If you want to query the entire collection:
Studentmodel.find ({}).then(doc => {console.log(doc); })Copy the code
You can see that all the records in the collection are printed.
4. Update operations
The update | updateOne | updateMany method
Create the update.js file
// update.js file
const StudentModel = require('./StudentModel'); / / update method takes two parameters, the first is the query conditions, the second is to change the value of the / / the name below for lisi records, amend the his age to 80 StudentModel. Update ({name:'lisi'}, {age: 80}).then(result => {
console.log(result)
})
Copy the code
Enter Robo3T, you can see the data is changed, switching to table mode is more intuitive:
Update is deprecated. Use updateOne, updateMany, or bulkWrite instead.
We should use updateOne, updateMany, or bulkWrite
Update updates all query results. The method is deprecated and has been replaced by updateMany. UpdateOne If multiple results are displayed, update only the first record. UpateMany Updates all the query results. BulkWrite provides batch write operations in a controllable order.
For the robustness of the code, we should replace the update method with the updateMany method as suggested.
In addition, the terminal output {n: 1, nModified: 1, OK: 1} means:
- N: 1: Indicates that one record is queried.
- “NModified: 1” : indicates that one record needs to be modified. (If the modified value is the same as the original value, the number of items to be modified is 0.)
- Ok: 1: One item is modified successfully.
5. Delete
Remove | removeOne | removeMany | bulkWrite method
Create the remote. Js file
// remove.js file
const StudentModel = require('./StudentModel'); Studentmodel.remove ({name: StudentModel) studentModel.remove ({name: StudentModel) studentModel.remove ({name: StudentModel) studentModel.remove ({name: StudentModel) studentModel.remove ({name: StudentModel) studentModel.remove ({name: StudentModel;'lisi'}).then((result) => {
console.log(result);
});
Copy the code
Enter Robo3T, you can see that there is no record of name lisi in the set:
When looking at the terminal output, similar to update, the prompt also suggests using a new method instead.
We are advised to use removeOne, removeMany, or bulkWrite
Remove Deletes all query results. This method is deprecated and has been replaced by removeMany. RemoveOne If multiple results are displayed, delete only the first record. RemoveMany Deletes all the query results. BulkWrite provides batch write operations in a controllable order.
In addition, the terminal output {n: 1, OK: 1, deletedCount: 1} is similar to the meaning of update.
We have now successfully CRUD (add, read, Update, Delete) the MongoDB database. Cheers ~
More advanced operations can be found in the Mongoose API documentation.
Four,
To sort out, the main contents are as follows:
node.js+MongoDB+mongoose
In the Mac environment setup, pay attention to use the latestMongoDB
Is installed.- How do I start and shut it down on the Mac
MongoDB
Service. - This paper introduces the
MongoDB
和mongoose
The basic core concepts of. - Use mongoose connection and add, delete and check MongoDB operations. You can use
Robo3T
To get a more intuitive view of the database.
The front end can also play with database development. Welcome to communicate ~
Article source address: github.com/yc111/mongo…
MacOS package manager Homebrew removes MongoDB
— Welcome to reprint, reprint please indicate the source: champyin.com/2019/10/10/…