nodejs中文教程-nodejs如何操作mongoDB的实例

nodejs中文教程 12年前 (2012) 工具猫
2,212 0

【转】学习了一下Nodejs和MongoDB,写了个示例程序,读取数据库中产品的列表。

var http = require("http"),
mongo = require("mongodb"),
events = require("events");
http.createServer(function(req, res) {
var products_emitter = new events.EventEmitter(),
// 创建到northwind数据库的链接。相当于use northwind
db = new mongo.Db("northwind", new mongo.Server('localhost', 27017, {}), {});
var listener = function(products) {
var html = [], len = products.length;
html.push('<!DOCTYPE html>');
html.push('<html>');
html.push('<head>');
html.push('<title>Nodejs</title>');
html.push('</head>');
html.push('<body>');
if(len > 0) {
html.push('<ul>');
for(var i = 0; i < len; i++) {
html.push('<li>' + products[i].name + '</li>');
}
html.push('</ul>');
}
html.push('</body>');
html.push('</html>');
res.writeHead(200, "Content-Type: text/html");
res.write(html.join(''));
res.end();
clearTimeout(timeout);
}
products_emitter.on('products', listener);
var timeout = setTimeout(function() {
products_emitter.emit('products', []);
products_emitter.removeListener('products', listener);
}, 10000);
db.open(function() {
// 打开名为products的表
db.collection("products", function(err, collection) {
// select * from products 相当于db.products.find()
collection.find(function(err, cursor) {
cursor.toArray(function(err, items) {
products_emitter.emit('products', items);
});
});
});
});
}).listen(8000);
console.log("Started");

原文地址:http://www.zhoumingzhi.com/2011/01/13/nodejs%E5%92%8Cmongodb%E5%88%9D%E4%BD%93%E9%AA%8C/

版权声明:工具猫 发表于 2012-12-09 19:16:04。
转载请注明:nodejs中文教程-nodejs如何操作mongoDB的实例 | 工具猫