const MongoClient = require('mongodb').MongoClient;
const url = 'mongodb://localhost:27017';
const dbName = 'mytestingdb';
const retrieveCustomers = (db, callback)=>{
const collection = db.collection('customers');
collection.find({}).toArray((err, customers) =>{
if(err) throw err;
console.log("Found the following records");
console.log(customers)
callback(customers);
});
}
const retrieveCustomer = (db, callback)=>{
const collection = db.collection('customers');
collection.find({'name': 'mahendra'}).toArray((err, customers) =>{
if(err) throw err;
console.log("Found the following records");
console.log(customers)
callback(customers);
});
}
const insertCustomers = (db, callback)=> {
const collection = db.collection('customers');
const dataArray = [{name : 'mahendra'}, {name :'divit'}, {name : 'aryan'} ];
collection.insertMany(dataArray, (err, result)=> {
if(err) throw err;
console.log("Inserted 3 customers into the collection");
callback(result);
});
}
MongoClient.connect(url,{ useUnifiedTopology: true }, (err, client) => {
console.log("Connected successfully to server");
const db = client.db(dbName);
insertCustomers(db, ()=> {
retrieveCustomers(db, ()=> {
retrieveCustomer(db, ()=> {
client.close();
});
});
});
});