我使用了 express 框架
目錄結構
db.js 檔案 function connectionDB(hostname, port) { //註釋地方暫時沒有使用。是把官方程式碼照抄下來 // var Db = require('mongodb').Db; var MongoClient = require('mongodb').MongoClient; var Server = require('mongodb').Server; // ReplSetServers = require('mongodb').ReplSetServers, // ObjectID = require('mongodb').ObjectID, // Binary = require('mongodb').Binary, // GridStore = require('mongodb').GridStore, // Grid = require('mongodb').Grid, // Code = require('mongodb').Code, // BSON = require('mongodb').pure().BSON, // assert = require('assert'); return new MongoClient(new Server(hostname, port), {native_parser: true}); } exports.connectDB = connectionDB; users.js 檔案 var db = require('./db'); router.get('/list', function (req, res) { var mongoclient = db.connectDB("localhost", 27017); mongoclient.open(function (err, mongoclient) { var db = mongoclient.db("app"); //app是資料庫名字 db.collection('list').find(function (err, result) { //list是document名字 result.toArray(function(err,r){ //r取出是 { _id: 5377f937b9cc9a6b70e3726d, // title: 'jqmobile', // listitem: [ 'java', 'php', 'maven' ] } var re = r[0]; console.info(re); res.render('list',re); 返回到試圖 list.ejs,我使用了express }); //res.send('respond with a resource'); }); }); });
list.ejs
<%= listitem %>