Nodejs Operation MongoDB Simple Example

Source: Internet
Author: User

Database operations

Mongo

Use TEST3;

Db.users.insert ({"Name": "AAA", "Email": "[email protected]"});

Nodejs Code Writing

Create a new test3 directory and edit the following file:

Package.json

{    "name": "Application-name",    "version": "0.0.1",    true,    "Scripts": {        "start": "Node App.js"    },    "dependencies": {        " Express ":" 3.4.4 ",        " Jade ":" * ",        " MongoDB ":" * ",        " Monk ":" * "     }}

App.js

varExpress = require (' Express ');varRoutes = require ('./routes '));varuser = require ('./routes/user '));varHTTP = require (' http ');varPath = require (' path ');varMONGO = require (' MongoDB ');varMonk = require (' Monk '));//vardb = Monk (' Localhost:27017/test3 ');//varApp =Express ();//All environmentsApp.set (' Port ', Process.env.PORT | | 3000); App.set (' Views ', Path.join (__dirname, ' views '))); App.set (' View engine ', ' Jade '); 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 Onlyif(' development ' = = = = App.get (' env ')) {app.use (Express.errorhandler ());}//App.get ('/', Routes.index); App.get ('/users ', user.list);//Create serverHttp.createserver (APP). Listen (App.get (' Port '),function() {Console.log (' Express server listening on port ' + app.get (' Port '));});//Hello WorldApp.get ('/hello ', Routes.hello);//User ListApp.get ('/userlist ', Routes.userlist (db));//New UserApp.get ('/newuser ', routes.newuser);//Add UserApp.post ('/adduser ', Routes.adduser (db));

Routes/index.js

Exports.index =function(req, res) {Res.render (' Index ', {title: ' Express '});} Exports.hello=function(req, res) {Res.render (' Hello ', {title: ' Hello, World '});} Exports.userlist=function(db) {return function(req, res) {varCollection = Db.get (' users '); Collection.find ({}, {},function(E, Docs) {Res.render (' UserList ', {                ' UserList ': Docs});    }); };} Exports.newuser=function(req, res) {Res.render (' NewUser ', {title: ' Add New User '});} Exports.adduser=function(db) {return function(req, res) {varUsername =Req.body.username; varUserEmail =Req.body.useremail; varCollection = Db.get (' users '); Collection.insert ({"Name": Username,"Email": UserEmail},function(err, doc) {if(Err) {Res.send (' There is a problem adding the information to the DB. '); } Else{res.location (' UserList '); Res.redirect (' UserList ');    }        }); };}

Routes/user.js

function (req, res) {    res.send (' respond with a resource ');}

Views/index.jade

extends Layoutblock content    h1= title    p Welcome to #{title}

Views/hello.jade

extends Layoutblock content    h1= title    p Welcome to #{title}

Views/userlist.jade

extends Layoutblock content    H1.        User List    ul        in  userlist            li                A (href= "Mailto:#{user.email}") = User.Name

Views/newuser.jade

extends Layoutblock content    h1= title    form#formadduser (Name= "AddUser", method= "POST", action= "/adduser")        input#inputusername (Type= "text", placeholder= "username", name= "username")        input#inputuseremail (Type= "text", placeholder= "UserEmail", name= "UserEmail")        Button#btnsubmit ( Type= "Submit") submit

Views/layout.jade

doctype htmlhtml    head        title= title        link (rel= ' stylesheet ', href= '/stylesheets /style.css ')    body        block content
Software run

CD Test3

NPM Install

Node App.js

Nodejs Operation MongoDB Simple Example

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.