Node. js Express from entry to cainiao (iii) -- node. js + express + mongodb database operations

Source: Internet
Author: User
Tags findone

After May 1, I came back and started this series.

After reading the previous series, we can complete a simple website without a database. Of course, there are few websites without database connection. Let's talk about the combination of node. js and mongodb.

Before we start, let's assume that we have installed and mastered mongodb installation and simple use, and a simple node. js operation for mongodb. If not, go to the mongodb authoritative guide or the Node. js and MongoDB hands-on tutorial.

This blog does not talk about the combination of node. js and mongodb. If you have any questions about this sentence, you can simply log on to the website. I used to asp.net object-oriented programming. When I first came into contact with js's functional asynchronous programming mode, I had a hard time.

I understand functional asynchronous programming as a programming method that conforms to people's habits of thinking. To put it simply, after completing Operation A, perform Operation B based on the input function. Let's look at the example.

This is a small example of the login, registration, and password change function. Technical points include mongodb and session.

Install express as described earlier

Modify the app. js file as follows:

App. js

Add the setting. js file to the root directory as follows:

Settings. js

1 module.exports = {2   cookieSecret: 'microblogbyvoid',3   db: 'mydb',4   host: 'localhost',5   port:'27017'6 };

Add the logon. js file to the route directory as follows:

Logon. js

Var user = require ('.. /modules/user'); exports. index = function (req, res) {res. render ('logon/Index', {title: 'logon'}) ;}; exports. logon = function (req, res) {var userService = new user ({username: req. body. username, password: req. body. pwd}); userService. logon (function (err, doc) {if (err) {res. send ('db error' + err);} if (doc) {req. session. userInfo = doc; res. send ('OK');} else {res. send ('false') ;}}) ;}; exports. register = function (req, res) {res. render ('logon/register ', {title: 'register new user'}) ;}; exports. processRegister = function (req, res) {var userService = new user ({username: req. body. username, password: req. body. pwd}); userService. get (function (err, result) {if (err) {res. send ('db error' + err);} if (result) {res. send ('user name already exist');} else {userService. add (function (err, result) {if (err) {res. send ('db error' + err);} if (result) {res. send ('OK');} else {res. send ('failed to add, please repeat ') ;}}}) ;}; exports. changePwd = function (req, res) {res. render ('logon/changePwd ', {title: 'change password', username: req. session. userInfo. username}) ;}; exports. processChangePwd = function (req, res) {var userSevice = new user ({username: req. session. userInfo. username, password: req. body. currPwd}); userSevice. get (function (err, doc) {if (err) {res. send ('db error' + err);} if (doc) {userSevice. updatePwd (req. body. newpwd, function (err, doc) {if (err) {res. send ('db error' + err);} if (doc) {res. send ('OK');} else {res. send ('modification failed') ;}}) ;}else {res. send (doc );}})};

Add the module folder and add the db. js and user. js files in the folder as follows:

Db. js

1 var settings = require('../setting');2 var Db = require('mongodb').Db;3 var Connection = require('mongodb').Connection;4 var Server = require('mongodb').Server;5 6 module.exports = new Db(settings.db, new Server(settings.host, settings.port, {auto_reconnect:true}),{safe:true});

 

User. js

Var db = require ('. /db'); function user (newUser) {this. username = newUser. username; this. password = newUser. password ;}; module. exports = user; user. prototype. get = function (callback) {var userTemp = new user ({username: this. username, password: this. password}); db. open (function (err, db) {if (err) {db. close (); callback (err);} else {db. collection ('users', function (err, collection) {if (err) {db. close (); callback (err);} else {var msg = {username: userTemp. username}; collection. findOne (msg, function (err, doc) {db. close (); if (doc) {var userTemp = new user ({username: doc. username, password: doc. password}); callback (err, userTemp);} else {callback (err, null) ;}});} user. prototype. add = function (callback) {var userTemp = new user ({username: this. username, password: this. password}); db. open (function (err, db) {if (err) {db. close (); callback (err);} else {var msg = {username: userTemp. username, password: userTemp. password}; db. collection ('users', function (err, collection) {collection. insert (msg, {safe: true}, function (err, result) {db. close (); callback (err, result) ;}) ;}}) ;}} user. prototype. logon = function (callback) {var userTemp = new user ({username: this. username, password: this. password}); db. open (function (err, db) {if (err) {db. close (); callback (err);} else {db. collection ('users', function (err, collection) {if (err) {db. close (); callback (err);} else {var msg = {username: userTemp. username, password: userTemp. password}; // do not know why. After the {safe: true} Option is added, only the id collection is returned. findOne (msg, function (err, doc) {db. close (); if (err) {callback (err)} else {callback (err, doc) ;}}}) ;}});} user. prototype. update = function (msg, updatamsg, callback) {db. open (function (err, db) {if (err) {db. close (); return callback (err);} db. collection ('users', function (err, collection) {if (err) {db. close (); return callback (err);} collection. update (msg, updatamsg, function (err, doc) {db. close (); callback (err, doc) ;})})} user. prototype. updatePwd = function (newPwd, callback) {var userTemp = new user ({username: this. username, password: this. password}); var msg = {"username": userTemp. username} var updatamsg = {"$ set": {"password": newPwd}; userTemp. update (msg, updatamsg, callback );}

This is the project structure

Have a good time ~~~~

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.