I am using mongodb as my database. I am trying to save the details(title, price and description) of a product to my database.
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 placed "*******" in place of password only for question). I could say that my database connection has been made as I can see the Connected message on my console.
Here is the save() function implementation in the product.js in models
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);
})
}
Here is the controller implementation:
exports.postAddProduct = (req, res, next) => {
const title=req.body.title;
const price=req.body.price;
const description=req.body.description;
const product = new Product(title, price, description);
product.save()
.then(result => {
console.log("Created product: "+ result);
res.redirect('/');
}
)
.catch(err => {
console.log(err);
})
}
Upon running my code when I submit the details of the product instead of being redirected to "/", I am getting a message as "no database found".
Please guide me to resolve this problem.
Top comments (0)