Node.js Operations MongoDB Database

Source: Internet
Author: User
Tags mongodb install node

Prepare: Install Node.js,mongodb,mongoose,webstorm

Here I use the mongoose to deal with. Mongoose is an object model tool for MongoDB that can work in asynchronous environments. Specific learning content See official website http://mongoosejs.com/docs/index.html

1, start to use Mongoose, must first install, open command line, execute $ npm Install Mongoose

2, connect the MongoDB database, add the following two lines of code inside the app.js.

var mongoose = require (' Mongoose ');
Mongoose.connect (' mongodb://localhost/test '); Connect to a database with test
Operation to here is basically a personal will, but the next concrete how to do the operation of the database, in the absence of instances of the case is still a bit tangled. I'm here to illustrate how to use a login registration as an example.

3, with Webstorm to create a new Express app project, so that the direct encapsulation of Express (), save yourself write trouble. Then modify the App.js as follows:

/**  * Module Dependencies.
 */var express = require (' Express ')  , routes = require ('./routes ')  , user = require ('./routes/user ')    , HTTP = require (' http ')  , PATH = require (' path ')  , Mongoose = require (' Mongoose ');


1 var app = Express ();
All Environments App.set (' Port ', Process.env.PORT | | 3000);
App.set (' views ', __dirname + '/views ');
App.set (' View engine ', ' Ejs ');
App.use (Express.favicon ());
App.use (Express.logger (' dev '));
App.use (Express.bodyparser ());
App.use (Express.methodoverride ());
App.use (App.router);


App.use (Express.static (Path.join (__dirname, ' public '));


Development only if (' development ' = app.get (' env ')) {  App.use (Express.errorhandler ());}
App.get ('/', routes.index);
App.get ('/log ', routes.login);
App.post ('/log ', routes.dologin);
App.get ('/reg ', routes.reg);


App.post ('/reg ', routes.doreg);  Mongoose Mongoose.connect (' mongodb://localhost/test_db '); 2 Http.createserver (APP). Listen (App.get (' Port '),function () {  Console.log (' Express server listening on port ' + app.get (' Port ');});
 

4, then define schema and model, these are the structure of the database table. Create a Models folder under the project root path, where a user.js is added to define the user table. The Models/user.js code is as follows.

var mongoose = require (' Mongoose ')
    , Schema = Mongoose. Schema
    , ObjectId = Schema.objectid;

var userschema = new Schema ({
      name:string
    , password:string
});

Module.exports = Mongoose.model (' User ', userschema);
Note that the last line, here is directly to the Userschema model to export, you can also directly export userschema,module.exports = Userschema, but to do so, and then use this table information to be a separate model.

5, the introduction of mongoose, add their own files, in the view of the new Login registration page, the bottom of the head of these include documents are also built themselves. First say registration page, the form processing path is/reg. Note The User name password input box I was directly using Name= "user[]" this form, so that the following can be directly through the user to obtain relevant information, in fact, not so can also.

<% include Header.ejs%>
<form action= "/reg" method= "POST" >
<input type= "text" Name= "User[name ] "/>
<input type=" password "name=" User[password ""/> <input type= "
submit" value= "Register"/>
</form>
<% include Footer.ejs%>
Next, modify the Doreg method, which is the function that handles registering events.

6, modify the Index.js, because you want to register the data in the database, so here need to refer to the fourth step above created model. The specific code is shown below.

var User = require ('.. /models/user ');
/
* Get home page.
*/


Exports.index = function (req, res) {
user.find ({}, function (err,users) {
res.render (' index ', {TITL  E: ' Express ', users:users});
});
};

Exports.reg=function (req,res) {
res.render (' Reg ', {title: ' Register Page '});
Exports.doreg=function (req,res) {
var user = new User (req.body.user);
User.save (function (err, user) {
if (!err) {
console.log (user);
Res.redirect ('/')
}
});
Console.log (Req.body.user);
};
This step to pay attention to why is Req.body.user, here is the front page to write directly with user[] This form of benefits, if the individual write name= "username", then this should be the following form.
var user = new User ({
	name:req.body[' username '],
	password:req.body[' password '
});
User.save is to submit the data to the database, use the method refer to the official document. Save the success of what you do after you play it yourself. You can also do some simple forms validation before saving, and so on.

7, through the login to say how to remove data from the database, continue to modify Index.js, as shown below.

var User = require ('..
/models/user ');
 /* Get home page. */Exports.index = function (req, res) {User.find ({}, function (err,users) {res.render (' index ', {title: ' Express
  ', users:users});
});
};
Exports.login=function (req,res) {res.render (' log ', {title: ' Login Page '});
    Exports.dologin=function (req,res) {var user = Req.body.user;                
                User.find (User,function (Err,docs) {if (!err) {if (docs!= ') {console.log (docs);
            return Res.redirect ('/');
                } else{Console.log (' Username or password incorrect ');
            Return Res.redirect ('/log ');
        }}else{Console.log ("something happend.");
}
    })
};
Exports.reg=function (req,res) {res.render (' reg ', {title: ' Register Page '});
    Exports.doreg=function (req,res) {var user = new User (req.body.user);
            User.save (function (err, user) {if (!err) {console.log (user); Res.redirect('/')
        }
    });
Console.log (Req.body.user);
 };
Here the Find () method to query the database, the use of methods do not explain. The first parameter user is the data to be queried, obtained from the input box, if not with user[] This form of the definition of the Name property, then here the same with {naem:req.body[' username '],password:req.body[' Password ']} such a writing. The callback function docs is the result returned from the database query.

The example ends here.


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.