db_control_red.js
1.21 KB
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
const MongoClient = require('mongodb').MongoClient;
const jokedoc = require('../joke_data/reddit_joke.json');
const dbname = 'redditjoke';
const collec = 'reddit';
const dboperation = require('./operations.js');
var url = "mongodb://localhost:27017/redditjoke";
//Create database
MongoClient.connect(url, { useNewUrlParser: true }, function(err, db) {
if (err) throw err;
console.log("Database created!");
db.close();
});
//Create collection
MongoClient.connect(url, { useNewUrlParser: true }, function(err, db) {
if (err) throw err;
var dbo = db.db("redditjoke");
dbo.createCollection("redditjokes", function(err, res) {
if (err) throw err;
console.log("Collection created!");
db.close();
});
});
//Storing data jokes.json data into mongodb
MongoClient.connect(url,{ useNewUrlParser: true }).then((client) => {
console.log('Connected correctly to server');
const db = client.db(dbname);
dboperation.insertDocument(db, jokedoc, collec)
.then((result) => {
console.log("Inserted Document:\n", result.ops);
return dboperation.findDocuments(db, collec);
})
.catch((err) => console.log(err));
})
.catch((err) => console.log(err));