# 密码登录
mongoose.connect('mongodb://username:password@host:port/database?options...');
1
# 无密码
mongoose.connect('mongodb://host:port/database?options...');
1
# 安装依赖
cnpm install mongodb
1
# 连接 MongoDB
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://username:password@119.45.212.92:27017/";
MongoClient.connect(url, { useNewUrlParser: true }, function(err, db) {
if (err) throw err;
var dbo = db.db("blog");
dbo.collection("members"). find({}).toArray(function(err, result) { // 返回集合中所有数据
if (err) throw err;
console.log(result);
db.close();
});
});
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
# Promise 数据操作
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://username:password@119.45.212.92:27017/";
MongoClient.connect(url, { useNewUrlParser: true }).then((conn) => {
console.log("数据库已连接");
const test = conn.db("testdb").collection("test");
// 增加
test.insertOne({ "site": "runoob.com" }).then((res) => {
// 查询
return test.find().toArray().then((arr) => {
console.log(arr);
});
}).then(() => {
// 更改
return test.updateMany({ "site": "runoob.com" },
{ $set: { "site": "example.com" } });
}).then((res) => {
// 查询
return test.find().toArray().then((arr) => {
console.log(arr);
});
}).then(() => {
// 删除
return test.deleteMany({ "site": "example.com" });
}).then((res) => {
// 查询
return test.find().toArray().then((arr) => {
console.log(arr);
});
}).catch((err) => {
console.log("数据操作失败" + err.message);
}).finally(() => {
conn.close();
});
}).catch((err) => {
console.log("数据库连接失败");
});
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
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