Showing
1 changed file
with
52 additions
and
0 deletions
DB_connect/db_control_user.js
0 → 100644
1 | +const MongoClient = require('mongodb').MongoClient; | ||
2 | +const jokedoc = require('../joke_data/user.json'); | ||
3 | +const dbname = 'userdb'; | ||
4 | +const collec = 'user'; | ||
5 | +const dboperation = require('./operations.js'); | ||
6 | +var url = "mongodb://localhost:27017/userdb"; | ||
7 | + | ||
8 | +//Create database | ||
9 | +MongoClient.connect(url, { useNewUrlParser: true }, function(err, db) { | ||
10 | + if (err) throw err; | ||
11 | + console.log("Database created!"); | ||
12 | + db.close(); | ||
13 | +}); | ||
14 | + | ||
15 | +//Create collection | ||
16 | +MongoClient.connect(url, { useNewUrlParser: true }, function(err, db) { | ||
17 | + if (err) throw err; | ||
18 | + var dbo = db.db("userdb"); | ||
19 | + dbo.createCollection("user", function(err, res) { | ||
20 | + if (err) throw err; | ||
21 | + console.log("Collection created!"); | ||
22 | + db.close(); | ||
23 | + }); | ||
24 | + }); | ||
25 | + | ||
26 | + | ||
27 | +//Storing data jokes.json data into mongodb | ||
28 | +MongoClient.connect(url,{ useNewUrlParser: true }).then((client) => { | ||
29 | + | ||
30 | + console.log('Connected correctly to server'); | ||
31 | + | ||
32 | + | ||
33 | + const db = client.db(dbname); | ||
34 | + | ||
35 | + dboperation.insertDocument(db, jokedoc, collec) | ||
36 | + .then((result) => { | ||
37 | + console.log("Inserted Document:\n", result.ops); | ||
38 | + | ||
39 | + return dboperation.findDocuments(db, collec); | ||
40 | + }) | ||
41 | + .catch((err) => console.log(err)); | ||
42 | + | ||
43 | +}) | ||
44 | +.catch((err) => console.log(err)); | ||
45 | + | ||
46 | + | ||
47 | + | ||
48 | + | ||
49 | + | ||
50 | + | ||
51 | + | ||
52 | + |
-
Please register or login to post a comment