/
collections.js
51 lines (43 loc) · 1.47 KB
/
collections.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
/*
Rapid Prototyping with JS is a JavaScript and Node.js book that will teach you how to build mobile and web apps fast. — Read more at
http://rapidprototypingwithjs.com.
*/
var mongodb = require('mongodb');
var url = require('url');
var log = console.log;
var dbUri = process.env.MONGOHQ_URL || 'mongodb://localhost:27017/test';
var connectionUri = url.parse(dbUri);
var dbName = connectionUri.pathname.replace(/^\//, '');
mongodb.Db.connect(dbUri, function(error, client) {
if (error) throw error;
client.collectionNames(function(error, names){
if(error) throw error;
//output all collection names
log("Collections");
log("===========");
var lastCollection = null;
names.forEach(function(colData){
var colName = colData.name.replace(dbName + ".", '')
log(colName);
lastCollection = colName;
});
if (!lastCollection) return;
var collection = new mongodb.Collection(client, lastCollection);
log("\nDocuments in " + lastCollection);
var documents = collection.find({}, {limit:5});
//output a count of all documents found
documents.count(function(error, count){
log(" " + count + " documents(s) found");
log("====================");
// output the first 5 documents
documents.toArray(function(error, docs) {
if(error) throw error;
docs.forEach(function(doc){
log(doc);
});
// close the connection
client.close();
});
});
});
});