db_control.js
2.1 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
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
const MongoClient = require('mongodb').MongoClient;
const jokedoc = require('../joke_data/jokes.json');
const dbname = 'jokeapi';
const collec = 'jokes';
const dboperation = require('./operations.js');
var url = "mongodb://localhost:27017/jokeapi";
//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("jokeapi");
dbo.createCollection("joke", 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));
// //will encapsulate all that database operations
// const assert = require('assert');
// exports.insertDocument = (db, document, collection, callback) =>{
// const coll = db.collection(collection);
// return coll.insert(document);
// };
// exports.findDocuments = (db, collection, input,callback)=>{
// const coll = db.collection(collection);
// return coll.find({"type": input}).toArray();
// }
// exports.removeDocuments = (db, document , collection, callback)=>{
// const coll = db.collection(collection);
// return coll.deleteone(document);
// }
// exports.updateDocuments = (db, document , update ,collection, callback)=>{
// const coll = db.collection(collection);
// return coll.updateOne(document, {$set: update}, null);
// }
// exports.getdata = (db, document, collection, input, callback =>{
// result = findDocuments(db,collection);
// return result;
// })