connecting 2c creating 2creading from mongo

Solutions on MaxInterview for connecting 2c creating 2creading from mongo by the best coders in the world

showing results for - "connecting 2c creating 2creading from mongo"
Caterina
06 Jul 2018
1const MongoClient = require('mongodb').MongoClient;
2// Connection URL
3const url = 'mongodb://localhost:27017';
4// Database Name
5const dbName = 'mytestingdb';
6
7const retrieveCustomers = (db, callback)=>{
8    // Get the customers collection
9    const collection = db.collection('customers');
10    // Find some customers
11    collection.find({}).toArray((err, customers) =>{
12        if(err) throw err;
13      console.log("Found the following records");
14      console.log(customers)
15      callback(customers);
16    });
17}
18
19const retrieveCustomer = (db, callback)=>{
20    // Get the customers collection
21    const collection = db.collection('customers');
22    // Find some customers
23    collection.find({'name': 'mahendra'}).toArray((err, customers) =>{
24        if(err) throw err;
25      console.log("Found the following records");
26      console.log(customers)
27      callback(customers);
28    });
29}
30
31const insertCustomers = (db, callback)=> {
32    // Get the customers collection
33    const collection = db.collection('customers');
34    const dataArray = [{name : 'mahendra'}, {name :'divit'}, {name : 'aryan'} ];
35    // Insert some customers
36    collection.insertMany(dataArray, (err, result)=> {
37        if(err) throw err;
38        console.log("Inserted 3 customers into the collection");
39        callback(result);
40    });
41}
42
43// Use connect method to connect to the server
44MongoClient.connect(url,{ useUnifiedTopology: true }, (err, client) => {
45  console.log("Connected successfully to server");
46  const db = client.db(dbName);
47  insertCustomers(db, ()=> {
48    retrieveCustomers(db, ()=> {
49        retrieveCustomer(db, ()=> {
50            client.close();
51        });
52    });
53  });
54});
55
similar questions