NodeJS加MongoDB应用入门
OS:Windows 7
1.下载安装MongoDB:http://www.mongodb.org/downloads
2.下载安装NodeJS:http://nodejs.org/
3.运行MongoDB,在cmd窗口运行:C:\mongodb\bin\mongod.exe --dbpath C:\mongodb\data\db
4.JavaScript代码例子。
Copy/Paste以下代码到js文件,例如start.js,放到文件夹c:\DebugTest下
var mongodb = require('mongodb'); var server = new mongodb.Server('localhost', 27017, {auto_reconnect:true}); var db = new mongodb.Db('testdb', server, {safe:true}); db.open(function(err, db){ if(!err){ console.log('connect db'); db.createCollection('testcoll', {safe:true}, function(err, collection){ if(err){ console.log(err); }else{ var item1 = {name:'Tom', age:"1"}; var item2 = {name:'Jerry', age:"2"}; collection.insert([item1,item2],{safe:true},function(err,result){ console.log(result); }); collection.find().toArray(function(err,docs){ console.log('find'); console.log(docs); }); collection.findOne(function(err,doc){ console.log('findOne'); console.log(doc); }); } }); }else{ console.log(err); } });
5.安装mongodb模块
打开cmd窗口
把文件目录切换到start.js文件夹
运行cmd命令:npm install mongodb
6.运行start.js
在cmd窗口运行:node c:\debugtest\start.js
窗口输出如下:
connect db
[ { name: 'Tom', age: '1', _id: 5300533001a7ec94188eb3df },
{ name: 'Jerry', age: '2', _id: 5300533001a7ec94188eb3e0 } ]
find
[ { name: 'Tom', age: '1', _id: 5300533001a7ec94188eb3df },
{ name: 'Jerry', age: '2', _id: 5300533001a7ec94188eb3e0 } ]
findOne
{ name: 'Tom', age: '1', _id: 5300533001a7ec94188eb3df }
/************************************
ldlchina
QQ:3110615
************************************/