First, the preparatory work:
1, start the Mongodb:bin directory run
2. Insert a piece of data into the test database:
Second, the official start:
1, through the application Generator tool express
to quickly create an application skeleton, refer to express Chinese network http://www.expressjs.com.cn/starter/generator.html;
2. Here I created an application called Firstapp:
The following application skeleton is quickly generated through the Express generator:
3, express4 default to Jade as a template, here I use Ejs, in the Package.json file dependencies added "Ejs": "*", here together with "Mongoose": "*" also added in. NOTE: * will tell NPM to "install the latest version".
The content of the modified file is this:
4, Next is to modify the views in the content, delete the default Jade file, add Index.ejs:
<!DOCTYPE HTML><HTML><Head> <title><%=title%></title></Head><Body> <P>Hi<%=User.username%></P></Body></HTML>
This adds an error page Error.ejs, you can see the wrong message
<!DOCTYPE HTML><HTML><Head> <title>Error</title></Head><Body><H1><%=message%></H1><H2><%= Error. Status%></H2><Pre><%= Error. Stack%></Pre></Body></HTML>
5. Modify the routing file Routes/index.js:
varExpress = require (' Express ');varRouter =Express. Router ();varMongoose = require (' Mongoose ')), Schema=Mongoose. Schema;varURI = ' Mongodb://localhost/test ';vardb =mongoose.createconnection (URI);varUser =NewSchema ({id: {type:string, index:true}, Username: {type:string}, Age: {type:string}});/*GET users listing.*/Router.get (‘/‘,function(req, res, next) {Db.model (' User ', user). FindOne ({username: "Charles"},function(err, user) {Res.render (' Index ', {title: ' Express ', user:user}); });}); Module.exports= Router;
Here I am connected to the test database.
6, so you can download the relevant package can be run.
After running the project will be more Node_modules folder, download good mongoose, Ejs and so on need to use modules.
7, implementation:, in the browser input http://localhost:3000/can see the results.
Express4+mongodb A simple example of getting started