版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u010046908/article/details/52739543
1.初始化数据
启动MongoDB服务,在test数据库中插入一条实例数据:
> 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模块
npm install mongodb
3.编写test.js测试连接
var 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("成功关闭数据库");
}
});