Search code examples
javascriptnode.jsexpressherokumongoose

Heroku logs error is Mongoose error uri parameter to openURI() must be a string and it is a string


I am trying to deploy my work on heroku and after solving some errors, one error is not getting fixed and i tried so many methods but all are failing

added : useNewUrlParser: true,useCreateIndex: true, app.use(express.urlencoded({extended: false}))

const express = require('express');
const passport = require('passport')
const cors = require('cors');
const app = express();
const hostname='localhost';
var port=  process.env.PORT || 8080;
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const route=require('./routes/api/Routes');



 // DB Config
const db = require('./config/keys').mongoURI

 // Connect to mongo
 mongoose
    .connect(db,{ useNewUrlParser: true,useCreateIndex: true, })
    .then(() => console.log('Connected to MongoDB'))
    .catch(err => console.log(err))


  app.use(bodyParser.json()); 
  app.use(bodyParser.urlencoded({ extended: true })); 
  app.use(express.json())
  app.use(express.urlencoded({extended: false}))
  app.use(cors())

  app.get('/test', (req,res) => res.send(`<h1>Deployed on Heroku</h1>`))

and the error in git bash is

State changed from starting to crashed
/app/node_modules/mongoose/lib/connection.js:434
 throw new MongooseError('The `uri` parameter to `openUri()` must be a ' 
 +
 MongooseError: The `uri` parameter to `openUri()` must be a string, got 
 "undefined". Make sure the first parameter to `mongoose.connect()` or 
 `mongoose.createConnection()` is a string.

on https://teamse7.herokuapp.com/test shows application error


Solution

  • I changed the connection to
    mongoose.connect('mongodb+srv://*********@********.mongodb.net/test? retryWrites=true', {useNewUrlParser: true}); mongoose.connection.once('open', function(){ console.log('Conection has been made!'); }).on('error', function(error){ console.log('Error is: ', error); });