Mongoose Study Note 2015-7-24

Source: Internet
Author: User

A burst of Byron teacher spoke about MongoDB's crud operations, including:

How to create a new database (use dbname), delete a database (use dbname →db.dropdatabase ()), add data (db. CollectionName. Insert ({}) to view the data in the table (db. CollectionName. Find), sorted (sort), the data is too many to take the first few (. limit), skip the first few (. skip), limit and skip together in the time of the page is the most favorite, such as a page is 5, then. Limit (5). Skip (5*n). Update data (db. collectionname. Update ($set)).

For details, refer to the MongoDB CRUD Operations of the official website

On the basis of learning MongoDB, we began to study how to operate MongoDB in Nodejs. Nodejs uses mongoose to manipulate MongoDB.

This is to ensure that the computer is equipped with MongoDB and Nodejs.

My entry document is this (Mongoose website) "This article is actually the translation and annotation of the entry document."

1. From the Nodejs operator, go to a folder where you want to put the project Execute command:npm install Mongoose, installed on the mongoose dependent package. Then create a new Getting-started.js file in the file. Then you want to run the database and enter the command in the Nodejs Terminal:node Getting-started.js

2. Open the Getting-started.js file, introduce the Mongoose module, and connect the mongoose to the specific database on MongoDB. Here you can specify which database to connect to, such as the test database.

1 var mongoose = require (' Mongoose '); 2 mongoose.connect (' mongodb://localhost/test ');

3. We are about to connect the ' test ' database after the second step is completed. We need the following code to check if the connection is successful.

1 var db = mongoose.connection; 2 db.on (' Error ', Console.error.bind (console, ' connection error: ')); 3 db.once (' Open ', function (callback) {4  console.log (' Database connection succeeded '); 5 });

Once the connection is successful, our callback function callback will execute. (Extraneous: You should check the usage of console.error and bind here.)

4. Everything starts with the schema, and the process of mongoose conduction data is this: the schema generates the model, and the model is used to generate the instance (document-level).

4.1 schema is used to define the rules for generating the contents of a database document as well as examples of methods, such as the following code definition schema, then generated in the MongoDB database will see the output format as

{"_id": ObjectId ("55b1cb286697a8bc17cce7b8"), "name": "Fluffy", "__v": 0},

where the ID is added by default, and is added randomly, __v is a version lock (for the moment do not know what to do) , is also added by default. The format of the rest of the content needs to be defined in the schema itself.

In the object structure of the schema constructor is the key:value structure, the key represents our property name, value represents the type of the property, and Mongoose now supports 8 types: string\number\date\buffer\boolean\ Mixed\objectid\array, these types, in addition to Mixed, ObjectId are schema.types properties, others are JavaScript-owned properties.

1 var Kittyschema = Mongoose. Schema ({2    name:string3 });

"Schema my understanding is similar to JS in the construction object in the class, inside can define the method of the object, you can define the properties of the object." The attribute name and property type defined in the schema are similar to the properties of the object defined in the JS constructed object. And the difference is that it takes one more step to generate the model before new type instances can be created. 】

4.2 Schema compilation forms the model. Note that the name passed in the model is kitten, and then it is the name of the table collection in the database, for example, if the incoming Kitteny in the database table will show the name Kittenies.

1 var Kitten = Mongoose.model (' Kitten ', kittyschema);

5. Now that the Schema,model is set up, the model can be used to generate the instance. Syntax is new

1 var silence = new Kitten ({name: ' Silence '}); 2 Console.log (silence.name); ' Silence '

6. As mentioned above, we can also in the new schema (.. ) to write the method to the generated instance. There are two methods, one is method, this is document-level, can only add methods to the generated object, and another is the static method, which can add methods to the model level. This time using method methods.

1 //Note:methods must is added to the schema before compiling it with Mongoose.model () 2 kittySchema.methods.speak = function () {3  var greeting = this.name4     ? "Meow name is" + this.name5    : "I don ' t has a name"; 6   Console.log (greeting); 7 }89 var Kitten = Mongoose.model (' Kitten ', kittyschema);

6.1 Once we build the instance again, we find that the instance object has already obtained the Speak () method.

1 var fluffy = new Kitten ({name: ' fluffy '}); 2 fluffy.speak (); "Meow name is Fluffy"

7. If you want to save the data to MongoDB, you can use the save method

1 Fluffy.save (function (err, fluffy) {2  if (err) return Console.error (err); 3   fluffy.speak (); 4 });

Note: All callback functions in Mongoose are in this form of function (Err,result), err is an error, and result is the outcome of the returned object (or after the query filter). 】

There are many built-in query APIs in 8.mongoose, such as Find,findone,count,update,remove, and many of the crud operations with MongoDB are very similar.

1 Kitten.find (function (err, kittens) {2  if (err) return Console.error (err); 3   Console.log (kittens); 4 })

9. OK, now you can enter node Getting-started.js in node. js to start the database, then open the MongoDB service and then enter the MongoDB operation in CMD to see if your data is uploaded successfully.

Roughly as follows:

--------------------------------------------------------------------------------------------------

Other considerations: Why use a database? Database in addition to additions and deletions can have other functions? What are the differences and linkages between NoSQL databases and relational databases?

Mongoose Study Note 2015-7-24

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.