Ubuntu11.10下 NodeJs操作 Mongodb

本文发布时间: 2019-Mar-22
通过NodeJS 读取并操作Mongodb数据库,与操作MySQL 一样,都需要安装一个驱动包。这里可以使用node-mongodb-native插件来操作,也可以使用Mongoose,Mongoose是基于node-mongodb-native开发的MongoDB nodejs驱动,可以在异步的环境下执行。node-mongodb-native插件下载地址:https://github.com/christkv/node-mongodb-native首先准备好Mongodb,前文有介绍Ubuntu11.10下安装Mongodb,并在test库里建立user数据表。保证Mongodb启动成功。1,使用默认驱动node-mongodb-nativevar http = require("http"), mongo = require("mongodb"), events = require("events");http.createServer(function(req, res) { var products_emitter = new events.EventEmitter(), // 创建到test数据库的链接。相当于use test db = new mongo.Db("test", new mongo.Server('127.0.0.1', 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>'); html.push('<h1>NodejsMongodb</h1>'); 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('user', listener); var timeout = setTimeout(function() { products_emitter.emit('user', []); products_emitter.removeListener('user', listener); }, 10000); db.open(function() { // 打开名为user的表 db.collection("user", function(err, collection) { // select * from user 相当于db.user.find() collection.find(function(err, cursor) { cursor.toArray(function(err, items) { products_emitter.emit('user', items); }); }); }); });}).listen(8000);console.log("Started");


(以上内容不代表本站观点。)
---------------------------------
本网站以及域名有仲裁协议。
本網站以及域名有仲裁協議。

2024-Mar-04 02:11pm
栏目列表