小东子的个人技术专栏

node.js 操作MongoDB数据库

1.初始化数据

启动MongoDB服务,在test数据库中插入一条实例数据:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
> 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模块

1
npm install mongodb

3.编写test.js测试连接

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
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("成功关闭数据库");
}
});

4.运行结果

这里写图片描述