how to use async and await to connect to mongoDB database? - node.js

I am new to JavaScript and currently learning mongoDB with node.
The code Bellow is in callback functions but i want to connect to mongoDB database using async and await with try and catch .
const mongoose = require("mongoose");
mongoose.connect("mongodb://localhost/selfdb");
mongoose.connection
.once("open", () => {
console.log("connection has been made!");
})
.on("error", (error) => {
console.log("connection error:", error);
});
I tried doing this way:
const mongoose = require("mongoose");
async function main() {
const uri = "mongodb://localhost/selfdb";
const client = new mongoose(uri);
try {
await client.connect();
console.log("connection has been made!");
} catch (e) {
client.error(e);
} finally {
await client.close();
}
}
main().catch(console.error);
but i got following error:
TypeError: mongoose is not a constructor
how could i do it the right way?
am i doing any silly mistake?

I believe the better way to connect is like this
const mongoose = require('mongoose')
const connectDB = async () => {
try {
const conn = await mongoose.connect(process.env.MONGO_URI)
console.log(`MongoDB Connected: ${conn.connection.host}`)
}
catch (error) {
console.log(error)
process.exit(1)
}
}
module.exports = connectDB
Mongo URI is in .env file, but you can replace it with your connection string (but more secure in .env file)
Then in server.js or index.js (entry file)
const connectDB = require('path_to_file')
connectDB()

I Tried this approach !! May be it could be helpful.
DBconn.js (MONGO_URL is from .env file & dev_db_url is optional here)
require('dotenv').config({ path: 'env/.env' });
const dev_db_url = 'local dev. db url is not defined.';
const mongoDB_URL = process.env.MONGO_URL || dev_db_url;
const dbOptions = {useNewUrlParser: true, useUnifiedTopology: true};
const connectDB = async (cb) => {
try {
await mongoose.connect(mongoDB_URL, dbOptions)
.then(() => {
cb();
console.log("Connected to Database");
})
} catch (error) {
console.error("Could not Connect to Database", error)
}
};
module.exports = connectDB;
Server.js (Server will start to listen only after successful DB Connect)
require('dotenv').config({ path: 'env/.env' });
const connectDB = require('./database/DBConn')
const port = process.env.PORT || 5000;
const express = require('express')
const app = express()
// Connecting to DB
connectDB(()=>{
app.listen(port, () => {
console.log(`Backend : NodeJS/express server started on http://localhost:${port}`)
})
});
Another Way :
DBconn.js
const mongoose = require("mongoose");
require('dotenv').config({ path: 'env/.env' });
const dev_db_url = 'local dev. db url is not defined.';
const mongoDB_URL = process.env.MONGO_URL || dev_db_url;
const dbOptions = {useNewUrlParser: true, useUnifiedTopology: true};
const connectDB = async () => {
try {
await mongoose.connect(mongoDB_URL, dbOptions);
} catch (error) {
console.error("Could not Connect to Database", error)
}
};
module.exports = connectDB;
Server.js (here we use .once method)
require('dotenv').config({ path: 'env/.env' });
const mongoose = require("mongoose");
const connectDB = require('./database/DBConn')
const port = process.env.PORT || 5000;
const express = require('express');
const app = express();
connectDB();
mongoose.connection.once('open', () => {
console.log('Connected to MongoDB');
app.listen(port, () => {
console.log(`Backend : NodeJS/express server started on http://localhost:${port}`)
})
});

Related

Connect mongodb v5 to nodejs

How to connect new mongodb v5 to nodejs
const express = require('express');
const app = express();
const { MongoClient } = require('mongodb');
const url = 'mongodb://localhost:27017';
const client = new MongoClient(url);
async function main() {
await client.connect();
}
const collection = client.db('internfeb').collection('dashboard');
const port = process.env.PORT || 7710;
app.get('/health',async(req,res) => {
const output = []
const cursor = collection.find({});
for await (const doc of cursor) {
output.push(doc)
}
cursor.closed;
res.send(output)
})
app.post('/addUser',async(req,res) => {
await collection.insertOne(req.body)
res.send('Data Added')
})
app.listen(port,() => {
main()
console.log(`Running on thr port ${port}`)
})
You should initialize collection after the client has connected:
const express = require('express');
const app = express();
const { MongoClient } = require('mongodb');
const url = 'mongodb://localhost:27017';
const client = new MongoClient(url);
let collection;
async function main() {
try {
await client.connect();
collection = client.db('internfeb').collection('dashboard');
} catch (err) {
console.log(err);
process.exit(1);
}
}
const port = process.env.PORT || 7710;
app.get('/health', async (req, res) => {
const output = [];
const cursor = collection.find({});
for await (const doc of cursor) {
output.push(doc);
}
cursor.closed;
res.send(output);
});
app.post('/addUser', async (req, res) => {
await collection.insertOne(req.body);
res.send('Data Added');
});
app.listen(port, () => {
main();
console.log(`Running on thr port ${port}`);
});

Mongo DB didn't connect with my node server

I'm new in node and mongo.
I'm trying to connect mongo db with my node server but this error appears.
Error:getaddrinfo ENOTFOUND locahost
[nodemon] app crashed - waiting for file changes before starting...
server.js
`const express = require('express');
require('colors');
const products = require('./data/products');
const dotenv = require('dotenv');
//dotenv config
dotenv.config();
const { connectDb } = require('./config/config')
connectDb();
const app = express();
app.get('/', (req, res) => {
res.send('<h1>Welcome to Node server</h1>')
})
app.get('/products', (req, res) => {
res.json(products);
})
app.get('/products/:id', (req, res) => {
const product = products.find(p => p.id === req.params.id);
res.json(product);
})
const PORT = 8080;
app.listen(process.env.PORT || PORT, () => {
console.log(`Server running in ${process.env.NODE_ENV} mode on port ${process.env.PORT}`.inverse.green)
})`
config.js
const mongoose = require('mongoose');
require('colors');
const connectDb = async () => {
try {
const conn = await mongoose.connect(process.env.MONGO_URI, {
})
console.log(`MongoDB connected ${conn.connection.host}`.yellow)
} catch (error) {
console.error(`Error:${error.message}`.inverse.red);
process.exit(1);
}
};
module.exports = { connectDb }
.env
PORT = 8080
NODE_ENV = development
MONGO_URI = mongodb://locahost:27017/local

connectDB is not a function

Hi I'm new to coding currently trying to set up a connection to my server.
Getting an error message:
"TypeError: connectDB is not a function"
This is my db.js file
const mongoose = require('mongoose')
const connectDB = async () => {
try {
const conn = await mongoose.connect(process.env.MONGO_URI, {
useUnifiedTopology: true,
useNewUrlParser: true,
useCreateIndex: true,
})
console.log(`MongoDB Connected: ${conn.connection.host}`)
} catch (error) {
console.error(`Error: ${error.message}`)
process.exit(1)
}
}
module.exports = { connectDB }
and this is my server.js file
const express = require('express')
const dotenv = require('dotenv')
const connectDB = require('./config/db')
const products = require('./seed/products')
dotenv.config()
connectDB()
const app = express()
server.get('/', (req, res) => {
res.send('API is running.........')
})
server.get('/api/products', (req, res) => {
res.json(products)
})
server.get('/api/products/:id', (req, res) => {
const product = products.find((p) => p._id === req.params.id)
res.json(product)
})
const PORT = process.env.PORT || 5000
server.listen(
PORT,
console.log(`Server running in ${process.env.NODE_ENV} port ${PORT}`)
)
Looking for some assistance I'm really new to coding so please forgive me if I posted wrongly.
check this out:
You are exporting mongoose from the db.js file. Try exporting the function connectDB you just created.
// between brackets just in case you need to export something else, ok?
module.exports = { connectDB }
Then import it like this:
const { connectDB } = require('./config/db')
const mongoose = require('mongoose')
const connectDB = async () => {
try {
const conn = await mongoose.connect(process.env.MONGO_URI, {
useUnifiedTopology: true,
useNewUrlParser: true,
useCreateIndex: true,
})
console.log(`MongoDB Connected: ${conn.connection.host}`)
} catch (error) {
console.error(`Error: ${error.message}`)
process.exit(1)
}
}
module.exports = { connectDB }
const express = require('express')
const server = express()
const dotenv = require('dotenv')
const { connectDB } = require('./config/db')
const products = require('./seed/products')
dotenv.config()
connectDB()
const app = express()
server.get('/', (req, res) => {
res.send('API is running.........')
})
server.get('/api/products', (req, res) => {
res.json(products)
})
server.get('/api/products/:id', (req, res) => {
const product = products.find((p) => p._id === req.params.id)
res.json(product)
})
const PORT = process.env.PORT || 5000
server.listen(
PORT,
console.log(`Server running in ${process.env.NODE_ENV} port ${PORT}`)
)

Mongodb query does not the show the expect result

I am using node and express server to run the mongoDb. For connection and schema I am using mongoose. i successfully connect the database and able to post the data by using postman but problem is it does not show the expected query. Mongodb returns me only the id not the query which is name and description
Here is models
const mongoose = require("mongoose");
const { Schema } = mongoose;
const form = new Schema(
{
name: { type: String },
description: { type: String }
},
{
timestamps: true
}
);
const formSubmit = mongoose.model("formSubmit", form);
module.exports = formSubmit;
This is my express server
const express = require("express");
const port = 5000;
const cors = require("cors");
const morgan = require("morgan");
const app = express();
const formSubmit = require("./models");
const mongoose = require("mongoose");
app.use(cors());
app.use(morgan("dev"));
mongoose
.connect(
"url",
{
useUnifiedTopology: true,
useNewUrlParser: true
}
)
.then(() => console.log("DB Connected!"))
.catch(err => {
console.log(err);
});
//get method
app.get("/show", async (req, res) => {
try {
const entrries = await formSubmit.find();
res.json(entrries);
} catch (error) {
console.log(error);
}
});
//post method
app.post("/post", async (req, res, next) => {
try {
const logs = new formSubmit(req.body);
const entry = await logs.save();
res.json(entry);
} catch (error) {
if (error.name === "ValidationError") {
res.status(422);
}
next(error);
}
});
app.listen(port, () => {
console.log(`Server is running port ${port}`);
});
I think the problem is you don't correctly save the documents to the collection, so when you retrieve them only _id fields display.
To be able to read request body, you need to add express.json() middleware to your server.js.
app.use(express.json());

Mongoose & MongoDB connection on production

What are best practicies to handle mongodb connection using mongoose on production?
This is my code
connectToDatabase.js
'use strict';
const mongoose = require('mongoose');
const mongodb = require('mongodb');
mongoose.Promise = require('bluebird');
const { Db, Server } = mongodb;
const database = 'test';
const connectToDatabase = (callback) => {
if (process.env.NODE_ENV == 'test') return false;
const db = new Db(database new Server('localhost', 27017));
db.open()
.then(() => {
mongoose.connect(`mongodb://localhost/${database}`, { config: { autoIndex: false } });
mongoose.connection
.once('open', () => {
console.log(`Connected to database ${database}`);
callback(db);
})
.on('error', (error) => {
console.warn('Warning', error);
});
});
};
module.exports = connectToDatabase;
app.js
const connectToDatabase = require('./connectToDatabase');
connectToDatabase(() => {
// run server
});
I don't know exactly what happening when connection to database is interrupted, Is mongoose trying connect to database again?

Resources