db.collection is not a function (using in 2024)

29 Views Asked by At

I am trying to connect MongoDB with node.js but not working as i taught Mongosh Version 2.1.4

I have installed every libraries that want and i order the code via files.

I made a folder config inside that connection.js file which contains:

const mongoClient = require('mongodb').MongoClient
const state = { db:null }
module.exports.connect=function(done){
    const url='mongodb://localhost:27017'
    const dbname='shopping'

    mongoClient.connect(url,(err,data)=>{
        if(err)
        return done(err)
    state.db=data.db(dbname)
    
    })
    done()
    
}

module.exports.get=function(){
    return state.db
}

I made a another folder helpers inside that product-helpers.js file which contains:

var db = require('../config/connection')
module.exports = {
    addProduct:(product,callback)=>{
        console.log(product);
        db.collection('product').insertOne(product).then((data)=>{
            callback(true)

        })
    }
}

And i have a file for admin panel admin.js which contains:

var express = require('express');
var router = express.Router();
var productHelper = require('../helpers/product-helpers')
/* GET users listing. */
router.get('/', function(req, res, next) {
  let products = [
    {
      name:'Samsung A15',
      category:'Mobile',
      description:'this is samsung set phone',
      image:'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSyMghPEOARrzvgJb9WjhGYSDXA3DuEPIlmGA&usqp=CAU'
    },
    {
      name:'Honor X6',
      category:'Mobile',
      description:'this is honor set phone',
      image:'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTzAofD1NQohCChcMJWQ40h23t1eL8StX_fzA&usqp=CAU'
    },
    {
      name:'Iphone 14',
      category:'Mobile',
      description:'this is apple set phone',
      image:'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcR267jdT1RX_Wsff-KT9MiGy7eSF_FjK-QbWpenIbHiMLK90UBiqpPCREIT24if9Bk50R4&usqp=CAU'
    },
    {
      name:'Vivo Y20',
      category:'Mobile',
      description:'this is vivo set phone',
      image:'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQmGBnugl9D6sCtQblqXMuOiDVmaC_5QYD1MA&usqp=CAU'
    }
  ]
  res.render('admin/view-products',{products , admin:true});
});
router.get('/add-product',function(req,res){
  res.render('admin/add-product')
});
router.post('/add-product',(req,res)=>{
  console.log(req.body);
  console.log(req.files.Image);

  productHelper.addProduct(req.body,(result)=>{
    res.render('admin/add-product')
  });
})


module.exports = router;

and in app.js i provide

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');
app.engine('hbs', hbs.engine({extname:'hbs',defaultLayout:'layout',layoutsDir:__dirname+'/views/layout/',partialsDir:__dirname+'/views/partials/'}));
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(fileupload());
db.connect((err)=>{
  if(err) console.log('conn error'+err);
  else   console.log('database connected to port 27017');

});
app.use('/', userRouter);
app.use('/admin', adminRouter);

and when i run in terminal it shows

GET /admin/add-product 304 22.615 ms - -
{
  Name: 'shuhaib',
  Category: 'mobile',
  Price: '5603.2',
  Description: 'super hot model'
}
{
  name: 'lol.png',
  data: <Buffer 89 50 4e 47 0d 0a 1a 0a 00 00 00 0d 49 48 44 52 00 00 02 58 00 00 02 56 08 02 00 00 00 0b 0e 6e fb 00 00 00 09 70 48 59 73 00 00 2e 23 00 00 2e 23 01 ... 96738 more bytes>,
  size: 96788,
  encoding: '7bit',
  tempFilePath: '',
  truncated: false,
  mimetype: 'image/png',
  md5: '155d2f982dfceb23abc6eac6226971da',
  mv: [Function: mv]
}
{
  Name: 'shuhaib',
  Category: 'mobile',
  Price: '5603.2',
  Description: 'super hot model'
}
POST /admin/add-product 500 55.478 ms - 4227

but when i see in database by opening mongosh-showdbs there is no folder called product the database is not connecting why

0

There are 0 best solutions below