I am trying to connect to atlas mongo db using node js. But getting the error TypeError: Cannot read property 'db' of null I have created the cluster at atlas and given complete rights to user aayushg and also created a db 'test'
index.js
const express = require('express')
const bodyParser= require('body-parser')
const app = express()
app.use(bodyParser.urlencoded({extended: true}))
const MongoClient = require('mongodb').MongoClient;
// replace the uri string with your connection string.
const url = "mongodb+srv://aayushg:<aayushg18>#cluster0-fatp8.mongodb.net/test?retryWrites=true&w=majority";
const client = new MongoClient(url, { useNewUrlParser: true });
client.connect((err, database) => {
db = database.db("test")
app.listen(3000, function () {
})
app.get('/', (req, res) => {
//res.send('PDP')
res.sendFile(__dirname + '/index.html')
})
app.post('/quotes', (req, res) => {
db.collection('devices').save(req.body, (err, result) => {
if (err) return console.log(err)
console.log('saved to database')
res.redirect('/')
})
})
})
SCREENSHOT OF CMD
So, the error was related to the credentials you are providing with the help of if(err) throw err you can see the error is regarding the credentials. Now, you have to add correct credentials it will work fine. you are using <aayushg18> instead of aayushg18 Thanks.
I have got your problem. You connection uri is not in correct format. Do not use <> sign when you input your password. Replace <aayushg18> by aayushg18 like following:
const uri = "mongodb+srv://aayushg:aayushg18#cluster0-fatp8.mongodb.net/test?retryWrites=true&w=majority";
Related
I understand that we need to use asynch and await while connecting db since models are loading before db connection happening so i have used and call the function in server.js Please look into my code and help me.
Connection.js
const mongoose = require('mongoose');
mongoose.set('strictQuery', true);
module.exports = async () => {
console.log(process.env.DB_URL);
await mongoose.connect(process.env.DB_URL, {
useNewUrlParser: true,
//useUnifiedTopology: true
}).then(()=>{
console.log("Database Connected");
}).catch (error => {
console.log("Database connectivity Error", error);
});
}
Server.js
const express = require('express');
const dotEnv = require('dotenv');
const { urlencoded } = require('express');
const cors = require('cors');
const dbConnection = require('./database/connection');
dotEnv.config({path:'./.env'});
const app = express();
// Database connection
// cors
app.use(cors());
app.use(express.json());
dbConnection();
app.use('/api/v1/domain', require('./routes/domainRoutes') );
app.get('/', (req, res, next)=>{
res.send("Hello From node aPI server");
});
// request payload middleware
app.use(express.json);
app.use(urlencoded({extended:true}))
const PORT = process.env.PORT || 3000;
app.listen(PORT, ()=>{
console.log(`Server Listen on port ${PORT}`);
});
// error handling middle ware
app.use(function(err, req, res,next){
console.error(err.stack)
res.status(500).send({
status: 500,
message:err.message,
body:{}
})
});
DomainService.js
const Domain = require('../database/models/DomainModel');
module.exports.createDomain = async (serviceData) => {
try {
let domain = new Domain({...serviceData})
return await domain.save();
} catch (error) {
console.log("Soemthing wrong: Service : Create Domain ", error);
throw new Error(error);
}
}
you can find full code here
https://github.com/vlpreddy/node-express-rest-api
I am trying to develop rest api's using nodeJs, tried to connect with mongoddb using mongoose. I am getting this timeout error since 2 days, i tried most of the solutions in the internet including using await and async.
So can someone please look into my code and help me.
Since I was stupid enough, I haven't installed mongodb in my system, so it was not connecting obviously. But I felt like it suppose to throw an error like
dude there is no mongodb in your system, how the heck do you think you
can create database and store the collections.
Any how people who are coming here with same error but a different reason can utilise following code and connect database using async and await functions as new version can load models with out even caring whether database is connected or not.
**database/connection.js**
const mongoose = require('mongoose');
mongoose.set('strictQuery', true);
module.exports = async () => {
//console.log(DB_URL);
await mongoose.connect(process.env.DB_URL, {
useNewUrlParser: true,
useUnifiedTopology: true
}).then(()=>{
console.log("Database Connected");
}).catch (error => {
console.log("Database connectivity Error", error);
});
}
you can import in any page and call the variable as a function
since it returns a promise function which is written below.
const dbConnection = require('./database/connection');
dbConnection();
I'm trying to make request to a postgreSQL DB being accessed by a Node + Express server that I've deployed on Heroku. This is the error im getting when running 'heroku logs': Error: connect ECONNREFUSED 127.0.0.1:5432, along with a couple other errors. I'm using axios on the frontend to make request.
Here is my server.js file:
// express
const express = require('express');
// environment variables
require('dotenv').config();
// data base connector
const db = require('./db');
// cors
const cors = require('cors');
// express instance
const app = express();
// use cors
app.use(cors());
// attach data to req.body
app.use(express.json());
// get all articles
app.get('/api/v1/articles', async (req, res, next) => {
try {
// query database
const results = await db.query('SELECT * FROM articles;');
// send results
res.status(200).json({
results: results.rows
});
// handle error
} catch (err) {
next(err);
}
});
// get individual article
app.get('/api/v1/articles/:id', async (req, res, next) => {
try {
// query database
const article = await db.query(`SELECT * FROM articles WHERE id = $1;`, [req.params.id]);
// send back data
res.status(200).json({
article: article
});
// handle error
} catch (err) {
next(err);
}
});
// get article's comments
app.get('/api/v1/articles/:id/comments', async (req, res, next) => {
try {
// query database
const comments = await db.query(`SELECT * FROM comments WHERE article_id = $1;`, [req.params.id]);
// send back data
res.status(200).json({
comments: comments
});
// handle error
} catch (err) {
next(err);
}
});
// add comment
app.post('/api/v1/articles/:id/comments', async (req, res, next) => {
try {
// post comment in database
const comment = await db.query(`INSERT INTO comments (article_id, author, text)
VALUES ($1, $2, $3) returning *;`, [req.body.article_id, req.body.author, req.body.text]);
// send comment back
res.status(201).json({
comment
});
// handle error
} catch (err) {
next(err);
}
})
// listen
const port = process.env.PORT || 3001;
app.listen(port, () => {
console.log(`Server now listening on PORT ${port}`);
});
I'm supposedly connected to my DB with the pg library, and the Pool gets the credentials from an .env file. I'm able to connect to the DB within pgAdmin and write queries, make tables etc.
Any help greatly appreciated
Check your database connection configuration. The error shows that it tries to connect to PostgreSQL on 127.0.0.1 which is LOOPBACK ip address. This means that is trying to access the server on your machine. You need to configure the connection by specifying the correct address for the server where PostgreSQL is running
Im trying to insert / Post data in my mongoDb database using exrpess and through Postman, however im at loss in how to perform it. I defined an url being "/api/post" which executes a request of post and asks for now only the "title". When I use postman to create some data, it returns to me as "undefined" with an empty object.
Here is the code:
const {MongoClient} = require('mongodb');
const express = require("express");
const mongoose = require("mongoose")
const app = express()
async function main() {
const uri = "mongodb+srv://dbUser1:<password>#movies.uxfxv.mongodb.net/Movies?retryWrites=true&w=majority";
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
const { schema } = mongoose;
MongoClient.connect(uri, function(err, db) {
if (err) throw err;
let dbo = db.db("Movies");
dbo.collection("Movies").find({}).toArray(function(err, result) {
if (err) throw err;
console.log(result);
app.get("/", (req, res) => {
res.json(result)
})
app.post("/api/post", (req, res) => {
const title = req.body
console.log(title)
res.json({
title
})
})
db.close()
})
})
main().catch(console.error)
Here is the Postman Req.
I would appreciate any feedback an help, thanks!
I am following a tutorial online to make a simple CRUD node/express/mongo application. I can get this code to connect to the data base fine, but when I try to submit a quote to be added to the database, the console simply logs the data I've entered, and the data never actually gets added to the database. If anyone could help me to understand why this isn't working, I'd appreciate it.
A possible issue may be, in MongoDB atlas my project is called testeru, my database is called test, and my collection is called quotes. I'm not sure if I improperly referenced this data?
I am running this on local host and I did whitelist my IP address in Atlas.
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
//mongodb
const MongoClient = require('mongodb').MongoClient
MongoClient.connect('mongodb+srv://OBSCURED:OBSCURED#cluster0.izcbs.mongodb.net/test?retryWrites=true&w=majority', { useUnifiedTopology: true })
.then(client => {
console.log('Connected to Database')
const db = client.db('test')
const quotesCollection = db.collection('quotes')
// app.use{}
// app.get{}
app.post('/quotes', (req,res) => {
quotesCollection.insertOne(req.body)
.then(result => {
console.log(result)
})
.catch(error => console.error(error))
})
// app.listen{}
})
.catch(error => console.error(error))
//Body parser
app.use(bodyParser.urlencoded({extended:true}))
app.listen(3000, function() {
console.log('Listening on 3000');
})
//Get request:
app.get('/', (req,res) => {
res.sendFile(__dirname + '/index.html');
})
//CREATE
app.post('/quotes', (req, res) => {
console.log(req.body)
})
I am Getting Error While Connecting My Node.js Application to Mlabs Database. I am Using the Below Code, Please Tell me Where I am Wrong.
var express = require('express');
var app = express();
const MongoClient = require('mongodb').MongoClient;
const MONGO_URL = 'mongodb://dbUser:dbpassword#ds132251.mlab.com:33623/testing11';
app.get('/', function(req, res) {
MongoClient.connect(MONGO_URL, { useNewUrlParser: true }, (err, db) => {
if (err) {
return console.log('Error While Connecting to mongodb');
}
db.collection("users").find({_id:"5b50e2d3e712fa3g8a8e9a76"}, function(err,result){
if(err){
console.log('Error While Finding data from your table');
}else{
console.log(result);
}
})
});
});
app.listen(process.env.PORT || 5000);
Thanks In Advance.
Using the same connection string in your code, I console.log the error and got "MongoNetworkError: failed to connect to server". To fix this, make sure the connection string
const MONGO_URL = 'mongodb://dbUser:dbpassword#ds132251.mlab.com:33623/testing11'
is correct
and also make sure that your network is fine and can connect to mlab.