Node. js operations on mongodb Databases

Source: Internet
Author: User
1. When using mongoose, install mongoose first. Open the command line and execute $ npminstallmongoose2. Connect to the mongodb database and add the following two lines of code to app. js. [Javascript] varmongooserequire (& amp; #39; mongoose & amp; #39;); mongoose. con...

1. When using mongoose, install mongoose first, open the command line, and execute $ npm install mongoose

2. Connect to the mongodb database and add the following two lines of code in app. js.


[Javascript]
Var mongoose = require ('mongoose ');
Mongoose. connect ('mongodb: // localhost/test'); // connect to a test database

Var mongoose = require ('mongoose ');
Mongoose. connect ('mongodb: // localhost/test'); // you can connect to a test database and perform operations on the database, there is still a bit of tangle in the absence of instances. Here, we use a logon registration as an example to describe how to use it.

3. Use webstorm to create a new Express App project. In this way, express () is encapsulated directly, saving your own writing troubles. Then modify app. js as follows:


[Javascript]
/**
* 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 ('view', _ dirname + '/view ');
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 '));
});

/**
* 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 ('view', _ dirname + '/view ');
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. Define the Schema and Model. These are the structure of the database table. Create a models folder under the project root path and add a user. js folder to define the user table. The models/user. js code is as follows.


[Javascript]
Var mongoose = require ('mongoose ')
, Schema = mongoose. Schema
, ObjectId = Schema. ObjectId;
 
Var UserSchema = new Schema ({
Name: String
, Password: String
});
 
Module. exports = mongoose. model ('user', UserSchema );

Var mongoose = require ('mongoose ')
, Schema = mongoose. Schema
, ObjectId = Schema. ObjectId;

Var UserSchema = new Schema ({
Name: String
, Password: String
});

Module. exports = mongoose. model ('user', UserSchema); pay attention to the last line. Here, the UserSchema Model is exported directly. You can also directly export UserSchema, module. exports = UserSchema. However, when using this table information, you have to create a Model separately.

 

5. After mongoose is introduced, add the corresponding files and create a new logon registration page in view. These include files are also created at the bottom of the header. Let's talk about the registration page first. The form processing path is/reg. Note that the user name and password input box is in the form of name = "user []", so that the user can be used directly to obtain relevant information. This is not the case.
[Javascript]
<% Include header. ejs %>
 
<% Include footer. ejs %>

<% Include header. ejs %>

<% Include footer. ejs %> next, modify the doReg method, which is a function that handles registration events.
6. Modify index. js. Because you want to store the data to the database during registration, you need to reference the model created in Step 4 above. The Code is as follows.


[Javascript]
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. 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 );
};

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. 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 should pay attention to why req. body. user: Here is the benefit of using user [] to directly write a page. If you write name = "username" separately, it should be in the following format.
[Javascript]
Var user = new User ({
Name: req. body ['username'],
Password: req. body ['Password']
});

Var user = new User ({
Name: req. body ['username'],
Password: req. body ['Password']
}); User. save is to submit the data to the database just now. For detailed usage, see the official documentation. You can perform any operation after the save operation is successful. You can also perform some simple form verification before saving.

7. log on to get data from the database and modify index. js, as shown below.


[Javascript]
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 ('user name or password is 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 );
};

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 ('user name or password is 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 we use the find () method to query the database. The usage is not explained. The first parameter user is the data to be queried. It is obtained from the input box. If the name attribute is not defined in the form of user [], {naem: req. body ['username'], password: req. body ['Password. 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.