node.js 操作MongoDB数据库 发表于 2017-01-14 | 字数统计: 271(字) | 阅读时长: 1(分) | 1.初始化数据启动MongoDB服务,在test数据库中插入一条实例数据: 12345678910111213141516> use part_0;switched to db part_0> db.user.insert({"username":"lidong"});WriteResult({ "nInserted" : 1 })> db.user.insert({"username":"lizirui","sex":"1"});WriteResult({ "nInserted" : 1 })> db.user.find();{ "_id" : ObjectId("57f4898418cde5e4b9fe7a92"), "username" : "lidong" }{ "_id" : ObjectId("57f4899918cde5e4b9fe7a93"), "username" : "lizirui", "sex" : "1" }> db.user.insert({"username":"liziqi","sex":"1"});WriteResult({ "nInserted" : 1 })> db.user.insert({"username":"lizihan","sex":"1"});WriteResult({ "nInserted" : 1 })> db.user.find();{ "_id" : ObjectId("57f4898418cde5e4b9fe7a92"), "username" : "lidong" }{ "_id" : ObjectId("57f4899918cde5e4b9fe7a93"), "username" : "lizirui", "sex" : "1" } 2.在Node.js中引入MongoDB模块1npm install mongodb 3.编写test.js测试连接1234567891011121314151617181920212223242526272829303132333435363738394041var mongo = require('mongodb');var host = "localhost";var port = 27017;//创建MongoDB数据库所在服务器的Server对象var server = new mongo.Server(host, port, {auto_reconnect:true});//创建MongoDB数据库var db = new mongo.Db('part_0', server, {saft:true});//数据库连接操作db.open(function(err, db){ if(err) { console.log('连接数据库发生错误'); throw err; } else{ console.log("成功建立数据库连接"); db.collection('user',{safe:true}, function(err, collection){ if(err){ console.log(err); }else{ console.log('-----------'); collection.find(function(error,cursor){ cursor.each(function(error,doc){ if(doc){ console.log("name:"+doc.username+" sex:"+doc.sex); } }); }); } }); db.close(); }});db.on('close',function(err,db){ if (err) {throw err;} else{ console.log("成功关闭数据库"); }}); 4.运行结果