Nodejs 邂逅 Mongodb
2013-08-25 20:42
204 查看
基于Nodejs和MongoDB,读取数据库中产品的列表
网上找了上面这段代码[原文],执行了下,访问http://127.0.0.1:8000/当然一开始什么也没有。
于是往数据库norhwind 的集合products(collection)插入了两条数据,shell 命令如下
注意不需要预先创建一个集合,在第一次插入数据时候会自动创建。
再次刷新页面http://127.0.0.1:8000/,可以看到
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://127.0.0.1:8000/当然一开始什么也没有。
于是往数据库norhwind 的集合products(collection)插入了两条数据,shell 命令如下
> use northwind switched to db northwind > db.products.insert({'name':'shanshan'}) > db.products.insert({'name':'sandy'})
注意不需要预先创建一个集合,在第一次插入数据时候会自动创建。
再次刷新页面http://127.0.0.1:8000/,可以看到
相关文章推荐
- NodeJS 与 MongoDB 的邂逅
- NodeJS 与 MongoDB 的邂逅
- NodeJS加MongoDB应用入门
- nodejs学习8:windows连接mongodb出现的错误解决办法
- Nodejs结合MongoDB
- NodeJS中MongoDB驱动mongodb使用简介
- 实战开发:nodejs(express)+mongodb+........简单博客系统代码
- 2016.11 MAC系统下安装mongodb 配合nodeJS简单使用mongodb
- nodejs与mongodb建立连接
- mongodb - nodejs
- MongoDB的nodejs 键值压缩driver
- 使用nodejs、mongodb、express、linux搭建社区网站(3)-页面与路由
- mongodb在nodejs上基本应用
- MAC系统下安装mongodb 配合nodeJS简单使用mongodb
- 朴灵:基于MongoDB与NodeJS构建物联网系统
- Nodejs对MongoDB模糊查询
- mongodb nodeJs聚合查询
- Nodejs中Mongodb的基本使用
- nodejs直接操作mongodb
- nodejs操作mongodb