I am trying to connect to mongodb. I have just started web development.
Here is my database.js code:
const mongodb= require('mongodb');
const MongoClient = mongodb.MongoClient;
let _db;
const mongoConnect= callback=>{
MongoClient.connect('mongodb+srv://pawan:*************@cluster0.vchvo.mongodb.net/myFirstDatabase?retryWrites=true&w=majority')
.then(client=>{
console.log('connected');
_db= client.db();
callback();
})
.catch(err=>{
console.log(err);
throw err;
})
}
const getDb=()=>{
if(_db){
return _db;
}
throw 'no database found';
};
exports.mongoConnect= mongoConnect;
exports.getDb= getDb;
(I have changed password to ******** only for the question)
Here is the Product.js(model) code
const mongodb = require('mongodb');
const getDb = require('../Util/database').getDb;
class Product {
constructor(title, price, description) {
this.title = title;
this.price = price;
this.description = description;
}
save() {
const db = getDb();
return db.collection('products')
.insertOne(this)
.then(result=>{
console.log(result);
})
.catch(err=>{
console.log("error from save in model"+ err);
})
}
}
module.exports= Product;
Upon running my node application I am able to view "connected" on my console. When after the line _db= client.db(); I do console.log(_db) I get result as [Object Object]
but when I call _db in the save() method of product.js model to establish connection I get its value as undefined due to which I get the final result as no database found
Please guide me so that I could find out what I am missing?
product.jscode as well? .mongoConnectand want to see if you call everythiung in correct order. Basically this code should work .