In order to save the user data and business data for a site, a database is usually required. MongoDB and node. JS are particularly well-matched because MongoDB is a document-based, non-relational database that is stored in Bson (the lightweight binary format of JSON), and the commands for managing databases such as additions and deletions are much like the JavaScript syntax. If you have access to MongoDB data in node. js, there will be a feeling of being a family, especially cordial.
I'm also going to use MongoDB as my database.
MongoDB uses collections (collection) and documents to describe and store data, collection is the equivalent of a table, document is equivalent to rows, but a relational database such as MySQL, the table structure is fixed, for example, a row is composed of several columns , the lines are the same, and MongoDB is different, a collection of multiple documents can have a different structure, more flexible.
Installation
Detailed guide is here: https://docs.mongodb.org/manual/tutorial/install-mongodb-on-windows/.
To https://www.mongodb.org/downloads download the installation package, the Windows system is the MSI file, I chose "Windows 64-bit r2+" this version.
Installation is very simple, you can default, you can also choose the installation location, I installed in the G-Disk MongoDB directory. When the installation is complete, the directory structure is this: G:\MongoDB\Server\3.0\.
Mongod, MONGO, and other tools are all in the bin directory under the 3.0 directory.
Start
To use MongoDB, you need to specify a folder for it to hold data, and I set up a folder named DB under G:\MongoDB.
Open cmd, enter the G:\MongoDB\Server\3.0\bin directory, execute "mongod–dbpath=g:\mongodb\db", will start MongoDB, see the following figure:
After MongoDB starts, it listens on a port waiting for the client to connect, and as you can see, the default listener port is 27017. You can change this port with the "–port" option, such as the "Mongod–port 28018–dbpath=g:\mongodb\db" command that starts MongoDB and listens on port 28018.
With MongoDB started, we can use MONGO (interactive shell) to manage the database. Execute MONGO directly in the bin directory and you will see:
The MONGO shell is connected to the test database by default and tells us that you can enter help to view the assistance. You can type help and enter to see what commands are available.
Note that the Mongod default boot without authentication, the client after the connection can be random operation, build a library, increase the deletion of all can be. If you want to restrict user privileges, you can configure them, I will go straight down here.
Database management
New Database
The MongoDB shell does not provide the ability to create a new database, but you can:
use accounts
db.createCollection (‘accounts’)
When you use "use accounts" to switch to the database named accounts, nothing actually happens. Only after you call db.createCollection, the new database is saved, and then you can use "show dbs" to see To the newly created library.
Delete the database
To delete the database, you need to switch to the specified library, and then call dropDatabase (). as follows:
use accounts
db.dropDatabase ()
After calling dropDatabase, you can use "show dbs" to view.
Create collection
It has been used before to create a new database, just call createCollection.
Show collection
such:
use accounts
show collections
Get a collection of specified names
To get the collection object, you can do this:
use accounts
coll = db.getCollection ("accounts")
Delete collection
To delete a collection, you need to call the drop () method of the collection object. such:
use accounts
coll = db.getCollection ("accounts")
coll.drop ();
Add documents to the collection
To add a document to a collection, you need to get the collection object first, and then call the insert (document) method. The document parameter is a JSON object. The following command adds two users to the accounts collection:
use accounts
coll = db.getCollection ("accounts")
coll.insert ({name: "ZhangSan", password: "123456"})
coll.insert ({name: "WangEr", password: "nicai"})
Find in collection
Using the find () method of the collection object, you can list all the documents in the collection. such:
use accounts
coll = db.getCollection ("accounts")
coll.find ()
The find () method with parameters can be searched according to a certain field:
coll.find ({name: "ZhangSan"})
Remove document from collection
Use the remove () method of the collection object to delete the document. Remove () without parameters will delete all documents in the collection. Remove () with parameters only deletes the document specified by the parameter. For example, the following:
use accounts
coll = db.getCollection ("accounts")
coll.insert ({name: "QianQi", password: "888888"})
coll.find ()
coll.remove ({name: "WangEr"})
coll.find ()
coll.remove ()
coll.find ()
Update documents in collection
The collection object provides two methods to update the document: save (object) and update (query, update, options).
Save can directly update an object. The following code changes ZhangSan's password to 567890:
coll.save ({_ id: ObjectId ("55cc25b360bcee730bafd2bf"), name: "ZhangSan", password: "567890"})
The following update method has the same effect as the save above:
coll.update ({name: "ZhangSan"}, {name: "ZhangSan", password: "567890"})
The second parameter update () of update () is an object that can specify the operator used for the update. For example, $ set can set the value of the field. The following code is equivalent to the previous one:
coll.update ({name: "ZhangSan"}, {$ set: {password: "567890"}});
Use mongoose to manage the database
Node.js has a database driver for MongoDB: mongodb. You can use "npm install mongodb" to install.
But using the mongodb module directly is powerful and flexible, but it is a bit cumbersome. I will use mongoose. If you are interested in the original driver module, you can start here: https://docs.mongodb.org/getting-started/node/client/.
mongoose is built on mongodb and provides Schema, Model and Document objects, which is more convenient to use.
We can use the Schema object to define the structure of the document (similar to the table structure), we can define the fields and types, uniqueness, indexing and verification. The Model object represents all documents in the collection. The Document object serves as a representation of a single document in the collection. mongoose also has Query and Aggregate objects, Query implements query, and Aggregate implements aggregation.
Information about these can be found here: http://mongoosejs.com/docs/guide.html.
Without further ado, see how to use it.
Install mongoose
Use express to prepare a TestMongoDB project, the command sequence is as follows:
express TestMongoDB
cd TestMongoDB
npm install
After executing the above command, use the following command to install mongoose:
npm install mongoose --save
This command will install mongoose and use it as a project dependency, and the MongoDB driver and regexp modules that mongoose depends on will also be automatically installed.
Use mongoose
It is recommended to read the official quick start tutorial of mongoose first: http://mongoosejs.com/docs/index.html. It's very well spoken. Although it is an E-text, it is easy to understand.
To understand the API used, see here: http://mongoosejs.com/docs/api.html. API looks a bit
Using mongoose, you can create new databases, create new collections, and perform CRUD operations on the documents in the collections. When writing code, you can verify whether the results meet the expectations against the mongo shell.
Create a new mongo.js file under TestMongoDB with the following content:
var mongoose = require (‘mongoose’);
mongoose.connect (‘mongodb: // localhost / accounts’);
var db = mongoose.connection;
db.on (‘error‘, console.error.bind (console, ‘connection error:‘));
db.once (‘open’, function () {
console.log (‘mongoose opened!’);
var userSchema = new mongoose.Schema ({
name: {type: String, unique: true},
password: String
},
{collection: "accounts"}
);
var User = mongoose.model (‘accounts’, userSchema);
User.findOne ({name: "WangEr"}, function (err, doc) {
if (err) console.log (err);
else console.log (doc.name + ", password-" + doc.password);
});
var lisi = new User ({name: "LiSi", password: "123456"});
lisi.save (function (err, doc) {
if (err) console.log (err);
else console.log (doc.name + ‘saved’);
});
});
The above file, directly execute the "node mongo.js" command to view the effect.
To use mongoose, first require, and then use the connect method to connect to the database. Connect prototype:
connect (uri, options, [callback])
The format of uri is similar: "mongodb: // user: [email protected]: port / database".
The connection object of mongoose defines some events, such as connected, open, close, error, etc., we can listen to these events.
In our sample code, I listened to the open event, defined the Schema in the callback function, and called mongoose.model to compile the Schema to get the Model object. It should be noted that the name of the collection specified when defining the Schema must be consistent with the first parameter of mongoose.model.
Once you get the Model object, you can perform operations such as adding, deleting, modifying, and checking. Model objects have find (), findOne (), update (), remove () and other methods, similar to our usage in the mongo shell. These methods have an optional callback, when you provide these callbacks, the results of the execution will be returned to you through this callback. If you do not provide them, these methods will return a Query object, you can then assemble new options through Query, and then call Query exec (callback) to submit the query.
When I searched WangEr's file in the code, I used callback instead of Query.
The Model object has a Model (doc) method, used to construct a document (Document). When creating a Lisi document, it is this save () method of the Document object that can save the document to the database.
Mongoose says so much. For detailed usage, please refer to the API documentation when you use it. Most APIs provide sample code fragments.
Other articles:
Getting started with Node.js development-use cookies to keep logged in
Getting started with Node.js development-using AngularJS built-in services
Getting started with Node.js development-simple examples of Angular
Getting started with Node.js development-using AngularJS
Getting started with Node.js development-using the jade template engine
Getting started with Node.js development-routing and middleware in Express
Getting started with Node.js development-Express installation and use
Getting started with Node.js development-HTTP file server
Node.js development entry-HelloWorld reanalysis
Introduction to Node.js development-environment construction and HelloWorld
Copyright statement: This article is an original article by bloggers and may not be reproduced without the permission of the bloggers.
Getting started with Node.js development-MongoDB and Mongoose