Creating mongodb database and inserted jokes.json datas into mongodb database('jokeapi')
Showing
2 changed files
with
65 additions
and
0 deletions
mongo.js
0 → 100644
1 | +const MongoClient = require('mongodb').MongoClient; | ||
2 | +const assert = require('assert'); | ||
3 | +const dboperation = require('./operations'); | ||
4 | +const jokedoc = require('./jokes/jokes.json'); | ||
5 | +const url = 'mongodb://localhost:27017/'; | ||
6 | +const dbname = 'jokeapi'; | ||
7 | +const collec = 'jokes'; | ||
8 | + | ||
9 | +var url = "mongodb://localhost:27017/jokeapi"; | ||
10 | + | ||
11 | +// Code for Creating database | ||
12 | +// MongoClient.connect(url, function(err, db) { | ||
13 | +// if (err) throw err; | ||
14 | +// console.log("Database created!"); | ||
15 | +// db.close(); | ||
16 | +// }); | ||
17 | + | ||
18 | +// Code for Creating a Collection | ||
19 | +// MongoClient.connect(url, function(err, db) { | ||
20 | +// if (err) throw err; | ||
21 | +// var dbo = db.db("jokeapi"); | ||
22 | +// dbo.createCollection("joke", function(err, res) { | ||
23 | +// if (err) throw err; | ||
24 | +// console.log("Collection created!"); | ||
25 | +// db.close(); | ||
26 | +// }); | ||
27 | +// }); | ||
28 | + | ||
29 | +MongoClient.connect(url).then((client) => { | ||
30 | + | ||
31 | + console.log('Connected correctly to server'); | ||
32 | + const db = client.db(dbname); | ||
33 | + | ||
34 | + dboperation.insertDocument(db, jokedoc, collec) | ||
35 | + .then((result) => { | ||
36 | + console.log("Inserted Document:\n", result.ops); | ||
37 | + | ||
38 | + return dboperation.findDocuments(db, collec); | ||
39 | + }) | ||
40 | + .catch((err) => console.log(err)); | ||
41 | + | ||
42 | +}) | ||
43 | +.catch((err) => console.log(err)); | ||
... | \ No newline at end of file | ... | \ No newline at end of file |
operations.js
0 → 100644
1 | +//will encapsulate all that database operations | ||
2 | +const assert = require('assert'); | ||
3 | + | ||
4 | +exports.insertDocument = (db, document, collection, callback) =>{ | ||
5 | + const coll = db.collection(collection); | ||
6 | + return coll.insert(document); | ||
7 | +}; | ||
8 | + | ||
9 | +exports.findDocuments = (db, collection, callback)=>{ | ||
10 | + const coll = db.collection(collection); | ||
11 | + return coll.find({}).toArray(); | ||
12 | +} | ||
13 | + | ||
14 | +exports.removeDocuments = (db, document , collection, callback)=>{ | ||
15 | + const coll = db.collection(collection); | ||
16 | + return coll.deleteone(document); | ||
17 | +} | ||
18 | + | ||
19 | +exports.updateDocuments = (db, document , update ,collection, callback)=>{ | ||
20 | + const coll = db.collection(collection); | ||
21 | + return coll.updateOne(document, {$set: update}, null); | ||
22 | +} | ||
... | \ No newline at end of file | ... | \ No newline at end of file |
-
Please register or login to post a comment