xuemoyao 2014-01-17
1、在mongodb创建将要读取的表
创建数据库mongotest
use mongotest;
向user表中插入数据
db.user.insert({ name:'flyoung', age:'18', sex:true });
2、安装node-mongodb-native
npm install mongodb
二、实例(node.js读取mongodb)
参考node-mongodb-native的文档:https://github.com/mongodb/node-mongodb-native
var mongodb = require('mongodb'); var server = new mongodb.Server("127.0.0.1",27017,{});//本地27017端口 new mongodb.Db('mongotest',server,{}).open(function(error,client){//数据库:mongotest if(error) throw error; var collection = new mongodb.Collection(client,'user');//表:user collection.find(function(error,cursor){ cursor.each(function(error,doc){ if(doc){ console.log("name:"+doc.name+" age:"+doc.age); } }); }); });
运行:
node mongodbTest.js
结果:
name:flyoung age:18