Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //database.js
- const mongodb = require('mongodb');
- const MongoClient = mongodb.MongoClient;
- let _db;
- const mongoConnect = (callback) => {
- MongoClient.connect(
- 'mongodb+srv://RanaM:201505093@cluster0.bitxd.mongodb.net/<dbname>?retryWrites=true&w=majority'
- , { useUnifiedTopology: true,
- useNewUrlParser: true
- })
- .then( client => {
- console.log('Connected!');
- _db = client.db('test');
- callback(client);
- })
- .catch(err => {
- console.log(err);
- throw err;
- });
- };
- const getDb = () => {
- if(_db){
- return _db;
- }
- throw 'No Database found';
- }
- exports.mongoConnect = mongoConnect;
- exports.getDb = getDb;
- //app.js
- const express = require('express');
- const adminRoutes = require('./routes/admin');
- const shopRoutes = require('./routes/shop');
- const bodyParser = require('body-parser');
- const path = require('path');
- const app = express();
- const errorController = require('./controllers/error');
- const mongoConnect = require('./util/database').mongoConnect;
- app.set('view engine', 'ejs');
- app.set('views', 'views');
- app.use(bodyParser.urlencoded({ extended: false}));
- app.use(express.static(path.join(__dirname, 'public')));
- app.use('/admin',adminRoutes);
- //app.use(shopRoutes);
- app.use(errorController.get404);
- mongoConnect((client) => {
- console.log(client);
- app.listen(3000);
- });
- //app.listen(3000);
- ///Sample Insert into Database.!
- exports.postAddProduct = (req, res, next) => {
- const title = req.body.title;
- const imageUrl = req.body.imageUrl;
- const price = req.body.price;
- const description = req.body.description;
- const product = new Product(title,imageUrl,description,price);
- product
- .save()
- .then( result => {
- console.log('Added Product.!');
- res.redirect('/admin/products');
- })
- .catch(err => {
- console.log(err);
- });
- };
- ///Using in Model
- const getDb = require('../util/database').getDb;
- class Product{
- constructor(title, price, description, imageUrl){
- this.title = title;
- this.price = price;
- this.description = description;
- this.imageUrl = imageUrl;
- }
- save(){
- const db = getDb();
- return db.collection('products')
- .insertOne(this)
- .then(result => {
- console.log(result);
- }).
- catch(err => {
- console.log(err);
- });
- }
- static fetchAll(){
- const db = getDb();
- return db.collection('test')
- .find().toArray()
- .then(products => {
- console.log(products);
- return products;
- })
- .catch(err => {
- console.log(err);
- });
- }
- }
- module.exports = Product;
Add Comment
Please, Sign In to add comment