how to connect mongo db in node.js?

abhishek rao
2 min readMay 22, 2019

use mongodb compasss for testing .

package.json

{

“name”: “com.rao”,

“version”: “1.0.0”,

“description”: “test”,

“main”: “app.js”,

“scripts”: {

“test”: “olacab”,

“start”: “node app.js”

},

“repository”: {

“type”: “git”,

“url”: “oo”

},

“keywords”: [

“oo”

],

“author”: “oo”,

“license”: “ISC”,

“dependencies”: {

“bluebird”: “³.5.4”,

“cookie-parser”: “¹.4.4”,

“express”: “⁴.17.0”,

“jade”: “¹.11.0”,

“mongodb”: “³.2.5”,

“mongoose”: “⁵.5.10”,

“morgan”: “¹.9.1”,

“nodemailer”: “⁶.1.1”,

“serve-favicon”: “².5.0”,

“webpack-dev-server”: “³.4.1”

},

“devDependencies”: {

“nodemon”: “¹.19.0”

}

}

use this below code in app.js class

const express = require(‘express’);

const bodyParser = require(‘body-parser’);

const product = require(‘./routes/product.route’);

const app = express();

const mongoose = require(‘mongoose’);

let dev_db_url = ‘mongodb://localhost:27017/testdb’;

const mongoDB = process.env.MONGODB_URI || dev_db_url;

console.log(‘mongoDB ‘,mongoDB);

mongoose.connect(mongoDB);

mongoose.Promise = global.Promise;

const db = mongoose.connection;

db.on(‘error’, console.error.bind(console, ‘MongoDB connection error:’));

app.use(bodyParser.json());

app.use(bodyParser.urlencoded({extended: false}));

app.use(‘/products’, product);

let port = 1234;

app.listen(port, () => {

console.log(‘Server is up and running on port numner ‘ + port);

});

now create a model class

const mongoose = require(‘mongoose’);

const Schema = mongoose.Schema;

let ProductSchema = new Schema({

_id: {type: String},

email: {type: String},

name: {type: String},

password: {type: String},

});

module.exports = mongoose.model(‘Product’, ProductSchema);

create a router class and add this below code

const express = require(‘express’);

const router = express.Router();

const product_controller = require(‘../controllers/product.controller’);

router.post(‘/insertRecord’, product_controller.insertRecord);

router.get(‘/product_update’, product_controller.product_update);

module.exports = router;

create a controller class and add this below code .

const Product = require(‘../model/product.model’);

exports.insertRecord = function (req, res) {

var email = req.body.email;

var password = req.body.password;

var obj = { email: email, password: password };

console.log(‘obj ‘,obj);

Product.db.collection(‘user’).insert(obj,function(err,product){

console.log(‘product ‘,product);

res.send(product);

});

};

exports.product_update = function (req, res) {

Product.db.collection(‘user’).find().toArray( function(err, docs) {

if(err) throw err;

console.log(docs);

res.send(docs);

});

};

--

--

abhishek rao
0 Followers

Software developer at Affle India.