Nodejs + MongoDB + ejs + Express implementation page display connection

Source: Internet
Author: User
Tags assert install mongodb mongoclient

(1) MONGO start service, please check http://www.cnblogs.com/he0xff/p/5820575.html

(2) Create a new file; JS Example: Hello.js

Installing NPM Install Ejs

NPM Install Express

NPM Install MongoDB

NPM Install Monk

Create a new view layer (see the definition in your hello.js)

/*
* @jackhe
* File from: https://docs.mongodb.com/getting-started/node/query/
*/
var mongoclient = require (' MongoDB '). Mongoclient;
var assert = require (' assert ');
var ObjectId = require (' MongoDB '). ObjectID;
var url = ' Mongodb://127.0.0.1:27017/test ';


var express = require (' Express ');
var path = require (' path ');
var app = Express ();
App.set (' Views ', Path.join (__dirname, ' views '));
App.set (' View engine ', ' Ejs ');

/* Connect to Database */
var MONGO = require (' MongoDB ');
var monk = require (' Monk ');
var db = Monk (' mongodb://127.0.0.1:27017/test ');


App.get ('/', function (req,res) {
var collection = Db.get (' test ');
Collection.find ({},function (E,docs) {
Console.dir (Docs);
Res.render (' Hello.ejs ', {
"UserList": Docs
});

});
Res.render (' Hello ', {userlist:collection}); Passing parameters to a page template allows you to pass strings and objects. and return the page template to the client. The template page is passed in JSON format.
});
App.listen (8888);

Then ejs the template

<! DOCTYPE html>
<title></title>

<body>

<div style= "border:1px solid red;color: #666; font-size:30px;" >
<% for (i=0; i< userlist.length; i++) {%>
<a><%= Userlist[i].name%></a>
<%}%>
</div>
</body>

And then run with node. Service

You will be able to access it through the browser.

localhost:8888/

Nodejs + MongoDB + ejs + Express implementation page display connection

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.