Developing Web applications with the "MEAN" technology stack (iii) building a database with MongoDB

Source: Internet
Author: User
Tags install mongodb mongodump

The previous article describes how to use Express to build a service-side MVC development architecture, this article we will detail this model layer, that is, the database access layer. Contains how to use MongoDB to build a database, and how to use mongoose to access data. MongoDB Installation and startup first we have to install MongoDB, first go to the official website (http://www.mongodb.org/downloads) Download the installation package, my development environment is windows, so download the ISO file under Windows, According to the tip of the installation is complete, there is no need for special choice. After installation, in order to be able to start MongoDB globally in cmd, we need to configure the environment variables, the bin directory under the installation directory is configured in the system variables, next, a new directory for the database files. I created a new directory for D:\mongodb\data\db, then run cmd, execute the command mongod--dbpath D:\mongodb\data\db, this time MongoDB is running, we can use the program to connect the database. The default port for database MongoDB is 27017, and we have a models folder in the project that has a data model attached to the database, with a mongodb.js, which is simple:
var mongoose = require (' Mongoose '); Mongoose.connect (' Mongodb://localhost/questionmaker ' ) = Mongoose;
is the standard COMMONJS module notation, the first reference Mongoose module, and then connected to the database, the external Exposure Mongoose module. You can see that we have access to the local Questionmaker database in the code. So first we have to have this database. Run cmd to create a database use Questionmakerdb.createcollection ("counters") This command creates a database named Questionmaker. and create a collection in the library counters (which we will use later), it must be written, otherwise the database cannot be created. The driver module is written, we can connect to the database after we reference the module in the other module. Using Mongoose to operate the database we see a module called Mongoose, which is a Nodejs module, Mongoose provides a schema, Model, documents object, it can be more intuitive operation of the database, So many people like this module, and we use it to manipulate the database in our project. In order to access the database in our familiar object-oriented way, we first create a schema based on the data structure of the question:
var New Schema ({     id:string,    qtype:number,    name:string,    content:string,    options: [        {            Name:string        }    ],    answer:string});
Schema can be understood as a template, according to this model, we can use Mongoose.model to create a question class, the code is as follows:
var Question = Mongodb.mongoose.model ("Question", Questionschema);
Using the question class to instantiate objects with many methods to access/manipulate the database, such as the Save method, you can save a document, which is a concept in MongoDB, similar to a record in our previous concepts. To minimize the exposure to data (encapsulation), I created a new Questiondao object that mimics the concept in Java and adds a DAO layer to provide data access. External exposure methods are defined on this object, such as the code to save records and update records as follows:
//Save QuestionsQuestionDAO.prototype.save =function(obj, callback) {varInstance =NewQuestion (obj); Instance.save (function(Err) {callback (Err,NULL); });}//Update QuestionsQuestionDAO.prototype.update =function(obj, callback) {question.findbyidandupdate (obj._id, obj, {},function(Err) {callback (Err,NULL); });}
Using the Save method and the Findbyidandupdate method provided by mongoose, the callback function can be passed after each operation, so that we can return the results of the database access to the controller layer. In addition, according to the business needs, we can write more methods, such as the list, get, remove, respectively, to obtain a list of questions, get questions, delete questions. The list method also implements the paging return data.  MONGODB implementation ID Self-increment ID is a common requirement of the database, in MySQL, as long as the specified field auto_increment, in MongoDB, there is no such method, it must be implemented in the code. We implement the questions collection ID self-increment according to the official solution. The ID auto-increment feature requires a secondary collection to be completed, which is the new counters that we used to record the current ID value. Execute Db.counters.save ({_id: "QuestionID", seq:0}) on the MongoDB command line to complete the initialization. _ID is a field provided by MongoDB by default, and we are assigned to QuestionID here in order to make a tag so that we can find this record later. The Counterschema is then created in Question.js and a counter class is generated to manipulate the counters collection with the following code:
var Counterschema = Schema ({    true},    default: 1 }}); var Counter = Mongodb.mongoose.model ("Counter", Counterschema);
Then, before Questionschema the Save method, we should go to counters to get the latest ID, can be implemented by the pre method, the code is as follows:
 questionschema.pre (' Save ', function   ( Next) { var  doc = this  ; Counter.findbyidandupdate ({_id:  ' QuestionID '}, {$inc: {seq:1}}, function   (Error, counter) { if   (Error)  return   next (error);        Doc.id  = Counter.seq;    Next (); });}); Questionschema.set ( ' Toobject ', {getters: true }); 
As a result, each time question executes the Save method, the function is called to obtain the most recent ID after the increment. Backup and import of database backup and import of course is necessary, for example, you can take this my backup files directly into the practice, so that the step-by-step creation of the steps are omitted. To back up a database you can use the Mongodump command using the following: Mongodump-h dbhost-d dbname-o dbdirectory Importing an existing database can use the Mongostore command as follows: Mongorestore-h dbhost-d Dbname–directoryperdb dbdirectory specific parameters can be searched on the internet, a lot of articles, which are no longer described in detail here. Does the client tool MongoDB have a client tool like MySQL? Of course, I am using Robomongo this tool, easy to use, the interface is as follows, we can try to use. Developing Web applications using the mean technology stack the trilogy is here, again with the address of the practiced hand project: Https://github.com/Double-Lv/QuestionMaker In addition, this series of articles is just an introductory level introduction, The code written and the database design basically belong to "toy code", write a project that you play. In the actual project, we also have to consider a variety of factors, performance, load and so on, more topics to be studied.

Developing Web applications with the "MEAN" technology stack (iii) building a database with MongoDB

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.