Node:操作MongoDB工具

前面

写在最前面,最近刚接触NodeJS.发现确实好用,然后又接着连接到MongoDB写了个小程序,程序并未写完.暂不发布,但是其中用到的工具是可以发布的.当然工具也还有很多细节需要补充.

先贴代码,后面慢慢优化.

NodeJS图标
image-2409

代码

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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
/*

 NodeJS连接MongoDB.v 0.9.1

 ======================================
 最新使用版本:
 NodeJS:v5.3.0
 MongoDB:v3.0.3
 Node-MongoDB驱动:v2.1.4

 需要使用:
 NodeJS(官网:http://www.nodejs.org)
 MongoDB(官网:http://www.mongodb.org)
 Node-MongoDB驱动:使用:npm install mongodb 进行安装.
 驱动文档:http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html

 @update 2016.1.6
 ============================================

 @version 0.9
 1.将文件中的增删改查公布出去[待优化增加更多的方法.]
 2.整理代码.
 3.外部简单调用测试.
 4.数据库、集合名称采用外部传入.

 @version 0.9.1
 1.完善部分函数调用(例如:单条/多条新增、统计一共多少条数据、聚合操作等).
 2.修改新增函数,使其能同时适用于多条和单条.
 3.为大部分函数新增options可选参数,并给出可选参数参考网址.


 @author prd.
 @version 0.1 2016.1.14
 @version 0.9 2016.1.16
 @version 0.9.1 2016.1.17

 */

//获取数据库驱动.
var mongodb = require("mongodb").MongoClient;

//数据库名称[外部传入]
var dbname = "";
//集合名称[外部传入]
var collectionsname = "";
/*
 接收数据库名称、集合名称,任一为空将抛出异常.

 @dbname 数据库名称
 @collectionsname 集合名称
 */
var nodeMongo = function (dbname, collectionsname) {
    if (dbname == null || dbname == "" || collectionsname == "" || collectionsname == null) {
        throw("数据库、集合名称缺一不可.");
    }
    this.dbname = dbname;
    this.collectionsname = collectionsname;
};


//数据库连接对象.
var dbobj = null;

//连接数据库,获取数据库连接实例.
var getDB = function (dbname, callback) {
    //数据库连接地址test=数据库名称
    var url = "mongodb://localhost:27017/" + dbname;
    if (dbobj == null) {
        mongodb.connect(url, function (err, db) {
            console.log("数据库连接成功");
            dbobj = db;
            callback(db);
        });
    } else {
        callback(dbobj);
    }
};


/*
 根据数据库集合名称,获取集合对象.

 本函数将自动获取数据库实例.
 */
var getCollection = function (dbname, collectionsname, callback) {
    //获得数据库实例
    getDB(dbname, function (db) {
        //获得指定集合,并返回.
        callback(db.collection(collectionsname));
    })
};

/*

 关闭数据库连接.
 */
var closeConnection = function (db) {
    if (db) {
        console.log("关闭数据库连接成功!~");
        dbobj = null;
        db.close();
    }
};

nodeMongo.prototype.ObjectID = require("mongodb").ObjectID;

/*
 新增


 @insertData 需要新增的数据
 @options 可选参数:
 http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#insertMany
 http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#insertOne
 @callback 回调函数
 */
nodeMongo.prototype.insertDocuments = function (insertData, options, callback) {
    getCollection(this.dbname, this.collectionsname, function (collections) {
        if (insertData instanceof Array) {
            collections.insertMany(insertData, options,
                function (err, result) {
                    console.log("成功新增数据.");
                    var reresult = result;
                    closeConnection(dbobj);//关闭连接.
                    callback(reresult);
                });
        } else {
            collections.insertOne(insertData, options,
                function (err, result) {
                    console.log("成功新增数据.");
                    var reresult = result;
                    closeConnection(dbobj);//关闭连接.
                    callback(reresult);
                });
        }
    });
};


/*
 批量处理数据
 参考:
 http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#bulkWrite

 @operations 需要处理的数据-数组
 @options 可选参数:
 http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#bulkWrite
 @callback 回调函数
 */
nodeMongo.prototype.bulkWriteDocuments = function (operations, options, callback) {
    getCollection(this.dbname, this.collectionsname, function (collections) {
        if (operations instanceof Array) {
            collections.bulkWrite(operations, options,
                function (err, r) {
                    console.log("处理成功.");
                    var reresult = r;
                    closeConnection(dbobj);//关闭连接.
                    callback(reresult);
                });
        }
    });
};

/*
 查询不重复的数据

 @key 需要查找的列.
 @query 查询条件.
 @options 可选参数:
 http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#distinct
 @callback 回调函数
 */
nodeMongo.prototype.distinctDocument = function (key, query, options, callback) {
    getCollection(this.dbname, this.collectionsname, function (collections) {
        collections.distinct(key, query, options,
            function (err, docs) {
                console.log("查询成功.");
                var reresult = docs;
                closeConnection(dbobj);//关闭连接.
                callback(reresult);
            });
    });
};


/*

 更新一条

 @oldData 数据库中需要更新的数据条件
 @options 可选条件:
 http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#updateOne
 @newData 新数据
 @callback 回调函数
 */
nodeMongo.prototype.updateDocumentOne = function (oldData, newData, options, callback) {
    getCollection(this.dbname, this.collectionsname, function (collections) {
        //更新一条
        collections.updateOne(oldData, newData, options,
            function (err, result) {
                console.log("数据更新成功!");
                var reresult = result;
                closeConnection(dbobj);//关闭连接.
                callback(reresult);
            });
    });
};


/*

 更新多条

 @oldData 数据库中需要更新的数据条件
 @newData 新数据
 @options 可选参数:
 http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#updateMany
 @callback 回调函数
 */
nodeMongo.prototype.updateDocumentMany = function (oldData, newData, options, callback) {
    getCollection(this.dbname, this.collectionsname, function (collections) {
        //更新多条
        collections.updateMany(oldData, newData, options,
            function (err, result) {
                console.log("数据更新成功!");
                var reresult = result;
                closeConnection(dbobj);//关闭连接.
                callback(reresult);
            });
    });
};

/*

 删除

 @deleteCondi 删除条件
 @options 可选参数:
 http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#deleteOne
 @callback 回调函数
 */
nodeMongo.prototype.deleteDocumentOne = function (deleteCondi, options, callback) {
    getCollection(this.dbname, this.collectionsname, function (collections) {
        collections.deleteOne(deleteCondi, options, function (err, result) {
            console.log("数据删除成功!");
            var reresult = result;
            closeConnection(dbobj);//关闭连接.
            callback(reresult);
        });
    });
};


/*

 删除多条

 @deleteCondi 删除条件
 @options 可选参数:
 http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#deleteMany
 @callback 回调函数
 */
nodeMongo.prototype.deleteDocumentMany = function (deleteCondi, options, callback) {
    getCollection(this.dbname, this.collectionsname, function (collections) {
        collections.deleteMany(deleteCondi, options, function (err, result) {
            console.log("数据删除成功!");
            var reresult = result;
            closeConnection(dbobj);//关闭连接.
            callback(reresult);
        });
    });
};


/*
 查询

 @query 查询条件
 @callback 回调函数,
 查询成功之后,数据将传递给回调函数
 */
nodeMongo.prototype.findDocuments = function (query, callback) {
    getCollection(this.dbname, this.collectionsname, function (collections) {
        collections.find(query).toArray(function (err, docs) {
            console.log("查询数据.");
            var reresult = docs;
            closeConnection(dbobj);//关闭连接.
            callback(reresult);
        });
    });
};


/*
 统计数量.

 @query 统计条件
 @options 可选参数:
 http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#count
 @callback 回调函数,统计结果通过此函数传递.
 */
nodeMongo.prototype.countDocuments = function (query, options, callback) {
    getCollection(this.dbname, this.collectionsname, function (collections) {
        collections.count(query, options, function (count) {
            console.log("统计数据.");
            var reresult = count;
            closeConnection(dbobj);//关闭连接.
            callback(reresult);
        });
    });
};


/*
 聚合查询文档.
 http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#aggregate

 @pipeline 查询条件.
 @options 可选参数:
 http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#aggregate
 @callback 回调函数,查询结果通过此函数传递.
 */
nodeMongo.prototype.aggregateDocuments = function (pipeline, options, callback) {
    getCollection(this.dbname, this.collectionsname, function (collections) {
        collections.aggregate(pipeline, options, function (err, result) {
            console.log("统计数据.");
            var reresult = result;
            closeConnection(dbobj);//关闭连接.
            callback(reresult);
        });
    });
};

//将此文件中的数据发布成一个扩展,供外部使用.
exports.nodeMongo = nodeMongo;