-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdatabase.js
58 lines (53 loc) · 1.5 KB
/
database.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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
var mongoClient = require('mongodb').MongoClient;
var assert = require('assert');
var connect = function (databaseName, callback) {
var url = 'mongodb://localhost:27017/' + databaseName;
console.log(url);
mongoClient.connect(url, function (err, database) {
if (err) {
console.log('Fail to connect MongoDB instance');
} else {
console.log('Success to connect MongoDB instance');
}
callback(err, database);
});
}
var findOne = function (databaseName, collectionName, target, callback) {
connect(databaseName, function (err, database) {
if (err) {
callback(err, null);
} else {
var collection = database.collection(collectionName);
collection.find(target).toArray(function (err, documents) {
callback(err, documents);
database.close();
});
}
});
}
var insertOne = function (databaseName, collectionName, doc, callback) {
connect(databaseName, function (err, database) {
if (err) {
callback(err, null)
} else {
var collection = database.collection(collectionName);
collection.insertOne(doc, function (err, result) {
callback(err, result);
database.close();
});
}
});
}
// 查找帐号
exports.findAccount = function (account, callback) {
findOne('macondo', 'account', {'account': account}, function (err, documents) {
callback(err, documents);
});
}
// 插入帐号
exports.insertAccount = function (doc, callback) {
console.log('注册账号:' + doc);
insertOne('macondo', 'account', doc, function (err, result) {
callback(err, result);
});
}