JS to the end: node Learning 9

Source: Internet
Author: User
Tags new set

Node. JS Database Chapter--mongoose ODM Introduction Mongoose

Almost all languages have a native database connection driver, this we have learned on the last time, such as Java Jdbc,mysql-connector, but the actual development in order to pursue efficiency will not use the original connection, not always establish a connection, the last one, Our registration and landing each write a connection operation, at least we should encapsulate a database connection file, should not be connected every time. To this end, Mongoose ODM was born, the goal is to simplify the database operations, packaging operations into a simple method, and provide data validation rules, security and other features.

What is ORM?

Object relational mapping abbreviation, which is an important concept in the development of objects, object-oriented language and web Products such as Microsoft's EntityFramework framework is provided to the ASP. NET development of the relational mapping tool, as well as the author of Java development in the SSH framework of Hibernate is also ORM products, in fact, it is the object-oriented language of the class (Pojo class, the kind of only The Get,set Class) matches the table in the database, matching the manifested Pojo object to a row of data in the database so that the developer only needs to pass the properties in the Get,set object, and then Save,update, A framework like hibernate automatically corresponds to a specific row in the database, and the database is modified! This enables powerful decoupling (no SQL statements in the development language), which allows developers to focus on code development without having to do what the database administrator does (or even need to know about the database language). The biggest drawback of ORM is that performance lags far behind native SQL statements, because things like hibernate actually encapsulate SQL statements that map objects to databases, and never run out of SQL statements to manipulate the database.

What is Mini ORM?

The author contacted Mini Orm in 2015 for their own start-up company to develop an ASP. Contact, the product used at that time is Petapoco. The emergence of Mini ORM is mainly to make up for the low performance of ORM, can be understood as a lite version of the ORM, removed some complex mapping methods, retaining the basic database operation method, and require some complex connection statements need to manually write SQL, that is, development with the basic method + Manual SQL Hybrid notation, this ORM to the developer's request is higher, but compared to pure SQL or a lot of simple and convenient, it can be said that both the functionality of the ORM, while improving performance, between SQL and ORM.

What is ODM?

Well, I was also the first to hear this noun, Object Document mapper abbreviation, previously I only know Orm, here I explored StackOverflow:

These are the answers that others ask about the difference between ORM and ODM, to the effect that:

MySQL is a relational database, so you need to use an ORM tool to map objects in your code into database data

Tools are: hibernate,entity framework,dapper, etc.

MongoDB is a document class database, and you need to use ODM to translate the objects in your code into database data.

Mandango is an ODM tool

As for this mandango ODM I looked at the GitHub official page that was designed for PHP to connect MongoDB with the ODM tool, which corresponds to the mongoose under node. js.

What is Mongoose?

Compared to the native MongoDB Drive, the first simplification of the mongoose is to assume that the site is using a database, which is also very common in MySQL, we generally use a site only one library! So the entire application only need one connection, everywhere is available, do not have to write the connection method every time!

Then, using mongoose without worrying about whether the database is connected or not, he caches the database operations instructions, which are like the ORM products, and then wait until the commit to connect to the database and write the instructions to the database. Reduces the number of connections, improves performance, and simplifies operational validation. This way we do not need to listen to every connection return function.

Simple test

Package.json

{    "name":"mongoose-test",    "version":"0.0.1",    "description":"a mongoose example",    "dependencies":{        "mongoose":"latest"    }}

Querying data

//Introduction of Mongoose ModuleMongoose= require("Mongoose");//Connect the database, you need to select a fixed library, then no more connection OperationMongoose.Connect(' Mongodb://localhost/test ');//define Model templatesvarSchema= Mongoose.Schema,ObjectId= Schema.ObjectId;varDataschema= New Schema({    Email:String,    Password:String});//Generate Object//The first parameter is the collection namevarUser= Mongoose.Model(' User ',Dataschema);varName= {Email:' devil '};//Query by Name fieldUser.Find(Name,function(Err,Data{    Console.Log(data);    Console.Log("\ n")});varPassword= {Password:' 123456 '};//Query according to password fieldUser.Find(Password,function(Err,Data{    Console.Log(data);    Console.Log("\ n")});

The data of this query is the database collection used by the login registration module built in the previous chapter user, the first time is to query the email as "devil" data, the second is the query password for "123456" data.

New data

//Introduction of Mongoose ModuleMongoose= require("Mongoose");//Connect the database, you need to select a fixed library, then no more connection OperationMongoose.Connect(' Mongodb://localhost/test ');//define Model templatesvarSchema= Mongoose.Schema,ObjectId= Schema.ObjectId;varDataschema= New Schema({    Email:String,    Password:String});//Generate Object//The first parameter is the collection namevarUser= Mongoose.Model(' User ',Dataschema);varSave= {Email:"[email protected]",Password:"Zzzz"};varUser= New User(save);//Generate new object, which is a new data in the corresponding data set//Save this new object, that is, insert operationUser.Save(function(ERR){    Console.Log("Already saved");})

This operation stores a row of data through the model's Save method

Update action

//Introduction of Mongoose ModuleMongoose= require("Mongoose");//Connect the database, you need to select a fixed library, then no more connection OperationMongoose.Connect(' Mongodb://localhost/test ');//define Model templatesvarSchema= Mongoose.Schema,ObjectId= Schema.ObjectId;varDataschema= New Schema({    Email:String,    Password:String});//Generate Object//The first parameter is the collection namevarUser= Mongoose.Model(' User ',Dataschema);User.Update({Email:"Devil"},{Password:"Hello"},function(ERR){    Console.Log("Password already changed");})

This operation will email "devil" The user, the password is changed to "Hello".

Delete operation

//Introduction of Mongoose ModuleMongoose= require("Mongoose");//Connect the database, you need to select a fixed library, then no more connection OperationMongoose.Connect(' Mongodb://localhost/test ');//define Model templatesvarSchema= Mongoose.Schema,ObjectId= Schema.ObjectId;varDataschema= New Schema({    Email:String,    Password:String});//Generate Object//The first parameter is the collection namevarUser= Mongoose.Model(' User ',Dataschema);User.Remove({Email:"[email protected]"},function(ERR){    Console.Log("[email protected] already removed");})

Here we delete the email "[email protected]" data

Analytic routines

The basic routines for using mongoose to make a database for pruning are:

    • Require Mongoose module in, Return to Mongoose Object
    • Connect using the Mongoose object Connect, with the parameter connection socket default: mongodb://localhost/database
    • Defining model Samples--schema
    • The model of the corresponding set is obtained according to the schema, which is a key step to obtain
    • Using Find,remove,save,update to perform basic operations on a database

Note 1

Note: Where the Save method needs to be explained separately, we find that except for the other three without the new Model () operation, that is, there is no need to generate objects, using static methods (called class methods in Java), such as find:

//Generate Object//The first parameter is the collection namevarUser= Mongoose.Model(' User ',Dataschema);varName= {Email:' devil '};//Query by Name fieldUser.Find(Name,function(Err,Data{    Console.Log(data);    Console.Log("\ n")});

Because they (find,remove,update) are in the collection of data already in the delete operation, except that save is a new operation, must generate a fresh object, therefore, the Save method is based on the method under the new object, need new object This step operation:

var  Save =  { email  :    password  :   "zzzz"   var  user =  new  user   (Save)  //Focus: Generate a new object, which is a new data in the corresponding data set  //to save this new object is the insert Operation  user . save  (function  (Err) { console .  ( "already saved" )  } )  

Note that the above code uses the new model of the Sao operation and set the corresponding properties, which is a bit like the new object under Java Hibernate and then use the Set method, or directly constructs the method to pass in the data, and finally save the operation to the database, The basic operation of ODM and ORM is very similar, it can be said that ODM is the "special ORM" which is specially built for the database of MONGO.

NOTE 2

What is a schema?

Remember, he is not a model, to understand the schema, you can think of it as a prototype model (JS is called prototype), is the model (template), the schema should be the database set of properties one by one corresponding to the collection (table) has a name, Then the schema in the provisions of the time will have name, or mistakenly think it is a new set or error. The schema is used to describe what the model looks like and how the model works, and the operation of the database takes place on the model rather than on the schema.

Note 3

The corresponding relationship between model and database collection.

To get the model first, you need to pass the Mongoose.model method and pass in the collection name, schema. For example:

var=newSchema({    email:String,    password:String});var=mongoose.model(‘User‘,dataSchema);

User is a model, the model method passed in the first name, if there is no third parameter, the default first parameter corresponds to the database collection name, note that the default designation will all be converted to lowercase + plural form, for example, this is the user, The collection in the database is called users!

Note 4

Set default values to prevent empty strings

var=newSchema({    email:{type:String,default:"[email protected]"},    password:{type:String,default:"123456"}});
More ways to do it

SQL statements are colorful, there are many keywords, where,limit,like and so on. I thought MongoDB was not a relational database may not exist or be different, in fact Mongoose also has these keywords, and is the use of similar thinkphp-like chain operations.

Querying data using chained operations

//Introduction of Mongoose ModuleMongoose= require("Mongoose");//Connect the database, you need to select a fixed library, then no more connection OperationMongoose.Connect(' Mongodb://localhost/test ');//define Model templatesvarSchema= Mongoose.Schema;varUserschema= New Schema({    Email:String,    Password:String});//Generate Object//The first parameter is the collection namevarUser= Mongoose.Model(' User ',Userschema);User.where(' Email ').eq(' devil ').exec(function(Err,Data{    Console.Log(data);});

The previous steps are the same, using the model's class method, but using a chained approach to the keyword one by one configuration.

Some other commonly used chained methods

Greater than less than

var=User.where(‘email‘).gt(1).find(function(err,data){    console.log(data);})

GT is greater than, LT is less than, EQ equals, neq not equal to

Note: Use find,exec effect to test down the same effect

Like statement

var=User.where(‘email‘).regex(/mail/).find(function(err,data){    console.log(data);})

There is no like keyword in mongoose, a regular expression is required for fuzzy queries. The Regex method can be used to enter regular expressions.

JS to the end: node Learning 9

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.