Connectors for Nodejs and MongoDB Mongoose

Source: Internet
Author: User


Brief introduction


Today we will learn mongoose, what is mongoose, it is in MongoDB what is the relationship between it, what it can be used to do, introduce mongoose before we first a brief look at MongoDB.



MongoDB is an open source NoSQL database, compared to MySQL-like relational database, it is more light and flexible, it is very suitable for use in the case of large data size, not strong transaction. At the same time, it is also an object database, no tables, rows and other concepts, there is no fixed pattern and structure, all the data stored in the form of documents (document, is an associative array of objects, its interior consists of attributes, a property corresponding to the value may be a number, string, date, array, or even a nested document.) ), the data format is JSON.



The introduction of MongoDB, we need to know mongoose.



1. What is Mongoose?



Mongoose is an object model tool for MongoDB and is a node-mongodb-native-developed MongoDB Nodejs driver that can be executed in an asynchronous environment. At the same time, it is also an object model library for MongoDB operation, which encapsulates some commonly used methods such as MongoDB's addition and deletion to document, so that Nodejs operation MongoDB database becomes more flexible and simple.



2. What can mongoose do?



Mongoose, because it encapsulates the usual processing method for MongoDB to document operation, let Nodejs operation MongoDB database become easy, easier, so easy!



Learn the above introduction, I believe you have a preliminary understanding and understanding of the mongoose, a beginning, a step, run it, juvenile!


Install references


We already know mongoose, and we know MongoDB. MongoDB is an object database that is used to store data; Mongoose is an object model library that encapsulates MONGODB operations and is used to manipulate the data.



OK, let's take the first step in manipulating the data.



1. Install Mongoose:

npm install mongoose
2. Quoting mongoose:

 var mongoose = require ("mongoose");
3. Connect to the database using "mongoose":

 var db = mongoose.connect ("mongodb: // user: [email protected]: port / database");
4. Execute the following code to check the default database test. Can the connection succeed?

 var mongoose = require ("mongoose");
 var db = mongoose.connect ("mongodb: //127.0.0.1: 27017 / test");
 db.connection.on ("error", function (error) {console.log ("Database connection failed:" + error);});
 db.connection.on ("open", function () {console.log ("------ Database connection succeeded! ------");});


Understanding collections
We have laid the foundation through the study of the previous section, and this section starts the specific operation of the MongoDB database. First, let's briefly introduce the MongoDB database again.

MongoDB-is an object database, without the concepts of tables, rows, and fixed schemas and structures. All data is stored in the form of a document (hereinafter referred to as a document) (Document, which is an associative array-type object, its internal Consists of attributes. The value of an attribute may be a number, string, date, array, or even a nested document.) We will learn how to create documents and insert content later.

In MongoDB, multiple Documents can form a Collection (hereinafter referred to as a collection), and multiple collections can form a database.

If we want to manipulate MongoDB data, we must first have the "document" that contains the data mentioned above. What does the document mean? Please see the following introduction.

Document-is the core concept of MongoDB. It is an ordered set of key-value pairs. Documents are represented as objects in JavaScript. It is also the basic unit of data in MongoDB, which is very similar to the rows in a relational database management system, but more expressive.

Collection-consists of a group of documents. If a document in MongoDB is compared to a row in a relational database, then a collection is equivalent to a table.

If we want to use Mongoose to create a "collection" and add, delete, modify, check, how to achieve it, here we must first understand Schema (data attribute model), Model, Entity.

OK, let ’s get to know them in depth!

Brief Schema
Schema-a database model skeleton stored in the form of a file, which cannot be directly connected to the database side, that is, it does not have the ability to operate the database, it is just a representation of the database model in program fragments, which can be said to be data Attribute model (table structure in the traditional sense), or the skeleton of a "collection" model.

So how to define a Schema, please see the example:

var mongoose = require ("mongoose");
 
var TestSchema = new mongoose.Schema ({
 name: {type: String}, // property name, type is String
 age: {type: Number, default: 0}, // age, type is Number, default is 0
 time: {type: Date, default: Date.now},
 email: {type: String, default: ‘‘}
});
The basic attribute types are: string, date, numeric, Boolean, null, array, embedded document, etc.

Model Brief
Model —— The model generated by the Schema construction, in addition to the database skeleton defined by the Schema, also has the behavior of database operations, similar to the class that manages database properties and behaviors.

How to create a Model through Schema, as the following example:

var db = mongoose.connect ("mongodb: //127.0.0.1: 27017 / test");
// Create Model var TestModel = db.model ("test1", TestSchema);
test1: the name of the collection in the database. When we add data to it, if test1 already exists, it will be saved to its directory. If it does not exist, the test1 collection will be created and then the data will be saved.

With a Model, we also have a golden key to operate the database. In the following content, we will learn to use the Model to add, delete, modify and check specific operations, so we must be familiar with his creation format!

If you want to do something with a collection, let it be handled by the Model model. To create a Model model, we need to specify: 1. the name of the collection, 2. the Schema structure object of the collection, satisfying these two conditions, we You will have a golden key to operate the database.

Brief description of Entity
Entity-An entity created by a Model that uses the save method to store data. Both the Model and the Entity can affect database operations, but the Model is more operational than the Entity.

Create an Entity using a Model, as shown in the following example:

 var TestEntity = new TestModel ({
 name: "Lenka", age: 36, email: "[email protected]"});
 console.log (TestEntity.name); // Lenka
 console.log (TestEntity.age); // 36
After the creation is successful, the Schema property becomes a public property of Model and Entity.

Create collection
Based on the previous content, we will start to learn the specific operations on the data. The following are definitions of some basic data. I believe that it is no stranger to you. Please review it carefully!

In order to facilitate the learning of the following content and improve your learning efficiency, the following basic data are closely connected with the following content, so you must define it in the following structure and do not modify it (the default database is test and the collection is test1).

 var mongoose = require ("mongoose");
 var db = mongoose.connect ("mongodb: //127.0.0.1: 27017 / test");
 var TestSchema = new mongoose.Schema ({
     name: {type: String},
     age: {type: Number, default: 0},
     email: {type: String},
     time: {type: Date, default: Date.now}
     });
 var TestModel = db.model ("test1", TestSchema);
 var TestEntity = new TestModel ({
     name: "helloworld",
     age: 28,
     email: "[email protected]"
     });
 TestEntity.save (function (error, doc) {
 if (error) {
    console.log ("error:" + error);
    }
 else {
    console.log (doc);}
 });


For more content and exercises, check out the free content I wrote:

http://www.hubwiz.com/class/543b2e7788dba02718b5a4bd



Nodejs and Mongodb connector Mongoose

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.