mongoose connects only to localhost - node.js

I always get "Listening at localhost" but the URL I put is from Mongo Atlas. And when I print the environment variable to the console I get it correctly. mongoose automatically ignores any url other than localhost.
I have tried to restart nodemon muiltiple times.
mongoose
.connect(process.env.DATABASE_URL, {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() => {
console.log(process.env.DATABASE_URL); //prints the correct url but mongoose connects to localhost
console.log("mongo connected");
// logEntry.collection.drop();
})
.catch((error) => console.log(error.message));

validate the connection using the below mentioned code snippet.
const express = require('express');
const app = express();
const socketio = require('socket.io');
const mongoose = require('mongoose');
const expressServer = app.listen(3001);
const io = socketio(expressServer);
mongoose.connect('mongodb+srv://<UserName>:<Password>#democluster0.abcde.mongodb.net?retryWrites=true&w=majority');
mongoose.connection.on('open', function (ref) {
console.log('Connected to mongo server.');
mongoose.connection.db.listCollections().toArray(function (err, names) {
console.log(names);
});
})
Refer the below link to gain the URL for the same..
https://docs.atlas.mongodb.com/tutorial/connect-to-your-cluster/

Related

How can I connect MongoDB with Node.js?

I am trying to connect MongoDB with my signup.js, but it's not connecting. I am unable to find the problem. How can I solve this?
Code of signup.js:
const express = require('express')
const app = express()
require("./db/mydb");
app.get('/', (req, res) => {
res.send('Hello World!')
})
app.listen(4000, () => {
console.log(`App listening on port 4000`)
})
Code of mydb.js:
const mongoose = require("mongoose");
mongoose.connect("mongodb://localhost:27017/mydata",{
useNewUrlParser:true,
useUnifiedTopology:true,
useCreateIndex:true
}).then(()=>{
console.log("connection successful")
}).catch((e)=>{
console.log("Not connected")
})
Error:
App listening on port 4000
Not connected
If the last log statement is replaced with console.log(e), the output is:
MongoParseError: option usecreateindex is not supported
Here you have a simple example of how to connect MongoDB to Node.js using Express.js and Mongoose on localhost obviously:
File server.js
const express = require("express");
const mongoose = require("mongoose");
const app = express();
const port = 3000;
app.get("/", (req, res) => {
res.send("Express and Mongoose connection!");
});
// Connect to db
mongoose
.connect("mongodb://localhost:27017/test")
.then(() => {
// Listen for requests
app.listen(port, () => {
console.log(
`Connected to DB & Server is listening at http://127.0.0.1:${port}`
);
});
})
.catch((error) => {
console.log(error);
});
And as we can read in the Mongoose documentation → no more deprecation warning options
useNewUrlParser, useUnifiedTopology, useFindAndModify, and
useCreateIndex are no longer supported options. Mongoose 6 always
behaves as if useNewUrlParser, useUnifiedTopology, and useCreateIndex
are true, and useFindAndModify is false. Please remove these options
from your code.
It was tested with: "express": "^4.18.1", "mongoose": "^6.6.5"

Postman: Connect ECONNREFUSED 127.0.0.1:5005

I have developed an API endpoint. It was working fine before. Unfortunately the project folder got corrupted (I recreated the files db.js and server.js). But now when I try to fetch data from API, I'm getting:
"connect ECONNREFUSED 127.0.0.1:5005"
The URL I'm using is localhost:
And my server is running on the same port i.e. 5005:
Can someone please elaborate what can be the problem? My hunch is that when I recreated the files I may have missed something:
db.js:
const mongoose = require('mongoose');
const userName = "myUsername"
const password = "myPassword"
const dbName = "comfyRooms"
const dbURL = `mongodb+srv://${userName}:${password}#mongo-cluster.damzf.mongodb.net/${dbName}?authSource=admin&replicaSet=atlas-s7z01e-shard-0&readPreference=primary&appname=MongoDB%20Compass&ssl=true`
mongoose.connect(dbURL, {useUnifiedTopology: true, useNewUrlParser: true})
let connection = mongoose.connection
connection.on('error', () => {
console.log('Unable to connect to MongoDB')
})
connection.on('connected', () => {
console.log("MongoDB connection established :)")
})
module.exports = mongoose
server.js
const express = require('express')
const app = express()
const dbConfig = require('./db')
const roomsRoute = require('./routes/roomsRoute')
app.use('/api/rooms', roomsRoute)
const port = process.env.PORT || 5005
app.listen(() => {
console.log("Node JS server listening on port " + port)
})
roomsRoute.js:
const express = require('express');
const router = express.Router();
const Room = require('../models/rooms');
router.get('/getallrooms', async (req, res) => {
try {
const rooms = await Room.find({});
return res.send(rooms);
} catch (error) {
return res.status(400).json({message: error});
}
});
module.exports = router;
I have attached the important files. Please let me know if any other information is missing. Thanks!
You are not passing the port variable to the listen function, you are just logging it
app.listen(() => {
console.log("Node JS server listening on port " + port)
})
This should work
app.listen(port, () => {
console.log("Node JS server listening on port " + port)
})

ExpressJS: localhost didn’t send any data

I am writing an app, when I start the server, its working nicely, its connecting to database. But when I start http://localhost:5000 from the browser, it does not respond for a minuite then the browser shows a message:
localhost didn’t send any data.
ERR_EMPTY_RESPONSE
Here is my app.js:
const express = require('express');
const app = express();
const cookieParser = require('cookie-parser');
const mongoose = require('mongoose');
app.use(cookieParser);
app.use(express.json());
//const userRouter = require('./routes/user');
//app.use('/user', userRouter);
const startApp = async () => {
try {
await mongoose.connect('mongodb+srv://username:pass#cluster0-dcytp.mongodb.net/test?retryWrites=true&w=majority',
{ useUnifiedTopology: true,useNewUrlParser: true });
console.log(`successfully connected to database`);
const port = process.env.PORT || 5000
app.listen(port, () => {
console.log(`server runnin at ${port}`);
});
} catch (error) {
console.log(error.message)
}
}
startApp();
app.get('/', (req, res) => {
console.log("I am in the root");
res.send("hello World");
})
Why server is not responding from the browser?
try
app.use(cookieParser())
instead of
app.use(cookieParser)
Reference
I had the same problem db is connected but not able to send data. it looks weird but it works for me.
Add a new database user with new password, use the new userName and passw to connect your mongoodb
this is the exact like to add new database user
here is my db connection may it helps you too
mongoose.connect(DATABASE_URL, { useNewUrlParser: true,useUnifiedTopology: true })
const db = mongoose.connection
db.on('error', (error) => console.error(error))
db.once('open', () => console.log('connected to database'))
app.use(express.json())

TypeError: Cannot read property 'db' of null

I am having issue connecting to mongodb atlas, getting the error below
let express = require('express')
let mongodb = require('mongodb')
let app = express()
let db
let connectionString = 'mongodb+srv://olumide:xxxxxxxx#cluster0-edskm.mongodb.net/todoApp?retryWrites=true&w=majority'
mongodb.connect(connectionString, {useNewUrlParser: true, useUnifiedTopology: true}, function(err, client){
db = client.db()
app.listen(3000)
})
app.use(express.urlencoded({extended: false}))
app.post('/create-item', function(req,res){
db.collection('item').insertOne({text: req.body.item}, function(){
res.send("thanks for submitting the form")
})
})
Error message
This is because the mongo.connect function is asynchronous. You will need to include the app.post function inside of the mongo.connect callback.
Something kind of like this should work:
let express = require('express')
let mongodb = require('mongodb')
let app = express()
app.use(express.urlencoded({extended: false}))
let connectionString = 'mongodb+srv://olumide:xxxxxxxx#cluster0-edskm.mongodb.net/todoApp?retryWrites=true&w=majority'
mongodb.connect(connectionString, {useNewUrlParser: true, useUnifiedTopology: true}, function(err, client){
const db = client.db()
app.post('/create-item', function(req,res){
db.collection('item').insertOne({text: req.body.item}, function(){
res.send("thanks for submitting the form")
})
})
app.listen(3000)
})
I figured out, in newer versions of MongoDB (3 and higher) they have essentially changed the way of connecting node server to the database. To establish a reusable connection (So that we can access the connected database from any other file), I created an async function in my db.js file where the connection is established and then exported it. In the end of the file, I have called the function. The code is as follows:
const {MongoClient} = require('mongodb')
const client = new MongoClient('mongodb+srv://todoAppUser:<password>#cluster0.6lvjr.mongodb.net/myDatabase?retryWrites=true&w=majority')
async function start(){
await client.connect()
console.log("Connected")
module.exports = client.db()
const app = require('./app')
app.listen(3000)
}
start()
and while calling it from another file:
const productCollection = require('./db').collection("product");
This code gives me no error and works perfectly fine. With the help of the above code, one can use this conveniently while following the MVC (Model-View-Controller) framework.
use mongoose connection as a different javascript file and import it to express script file
database.js
let mongoose = require('mongoose');
const server = '127.0.0.1:27017'; // REPLACE WITH YOUR DB SERVER
const database = 'test'; // REPLACE WITH YOUR DB NAME
class Database {
constructor() {
this._connect()
}
_connect() {
mongoose.connect(`mongodb://${server}/${database}`,{ useUnifiedTopology: true ,useNewUrlParser: true, useFindAndModify: false})
.then(() => {
console.log('Database connection successful')
})
.catch(err => {
console.error('Database connection error')
})
}
}
module.exports = new Database()
strong text

How can I display my mongoDB query as json using express?

When I use nodemon to start my express server, it constantly loads in the browser and will not load any of my application.
This is the code in my dbconn.js and app.js files. I cannot figure out how to pull and display my query in order to verify my connection to the db. I am a total beginner in using mongoDB and express. Please help.
It is not throwing any exceptions, so I can't figure out what I am doing wrong.
const mongoose = require('mongoose')
const MongoClient = require('mongodb').MongoClient;
const express = require('express');
const router = express.Router();
const uri ='mongodb+srv://<username>:<password>#wager0-mhodf.mongodb.net/test?retryWrites=true&w=majority';
const client = new MongoClient(uri, { useUnifiedTopology: true, useNewUrlParser: true });
client.connect(err => {
console.log("Connected successfully to server");
router.get('/', function(req, res, next) {
const collection = client.db("wager0").collection("gameTypes");
// Get first two documents that match the query
collection.find({a:1}).limit(2).toArray(function(err, docs) {
res.json({length: docs.length, records: docs});
});
client.close();
});
});
module.exports = router;
var dbconnRouter = require('./services/dbconn');
app.use('/dbconn', dbconnRouter);

Resources