MongooseError: The `uri` parameter to `openUri()` must be a string, got "undefined"

Hello! Help Wanted! Nodejs development environment. Connecting to the database in the Mongodb Atlass cloud
File: myApp.js

require('dotenv').config();
const mongoose = require('mongoose');
mongoose.connect(process.env.MONGO_URI);
mongoose.connect("mongodb://localhost:27017/monprojectWee", {

  useNewUrlParser: "true",
  useUnifiedTopology: "true"

})
mongoose.connection.on("error", err => {

  console.log("err", err)

})
mongoose.connection.on("connected", (err, res) => {

  console.log("mongoose is connected")

})

let Schema = mongoose.Schema;
let personSchema = new Schema({
  name: {
    type: String,
    required: true
  },
  age: Number,
  favoriteFoods: [String]
});

let Person = mongoose.model('Person', personSchema);

var createAndSavePerson = function() {
  let person = new Person({name: 'EDOUKA EPOH WILFRID', age: 34, favoriteFoods: ['ananas', 'bananas', 'cakes']});
  person.save(function(err, data) {
    if(err){
      console.log(err)
    }else{
      console.log(data)
    }
  });  
};

/** **Well Done !!**
/* You completed these challenges, let's go celebrate !
 */

//----- **DO NOT EDIT BELOW THIS LINE** ----------------------------------



exports.PersonModel = Person;
exports.createAndSavePerson = createAndSavePerson;
exports.findPeopleByName = findPeopleByName;
exports.findOneByFood = findOneByFood;
exports.findPersonById = findPersonById;
exports.findEditThenSave = findEditThenSave;
exports.findAndUpdate = findAndUpdate;
exports.createManyPeople = createManyPeople;
exports.removeById = removeById;
exports.removeManyPeople = removeManyPeople;
exports.queryChain = queryChain;

sample.env

MONGO_URI='mongodb+srv://mon-project-wee:monproject@monprojectwee.brqps.mongodb.net/monprojectWee?retryWrites=true&w=majority'

Please help who can. I’m new, I’m learning

Your project link(s)

solution: https://replit.com/@weeyde/boilerplate-mongomongoose-3

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.63 Safari/537.36

Challenge: Create and Save a Record of a Model

Link to the challenge:

You can’t use the localhost connection string. Use the connection string you get from MongoDB Atlas.

If you have it in the environment variable then remove the second mongoose.connect call.

mongoose.connect(process.env.MONGO_URI);
// remove this mongoose.connect and move the option object to the above mongoose.connect
mongoose.connect("mongodb://localhost:27017/monprojectWee", {

  useNewUrlParser: "true",
  useUnifiedTopology: "true"

})

After deleting this snippet of code I still get this error.

> node server.js

Your app is listening on port 3000
(node:310) UnhandledPromiseRejectionWarning: 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.
    at NativeConnection.Connection.openUri (/home/runner/boilerplate-mongomongoose-3/node_modules/mongoose/lib/connection.js:686:11)
    at /home/runner/boilerplate-mongomongoose-3/node_modules/mongoose/lib/index.js:330:10
    at /home/runner/boilerplate-mongomongoose-3/node_modules/mongoose/lib/helpers/promiseOrCallback.js:32:5
    at new Promise (<anonymous>)
    at promiseOrCallback (/home/runner/boilerplate-mongomongoose-3/node_modules/mongoose/lib/helpers/promiseOrCallback.js:31:10)
    at Mongoose._promiseOrCallback (/home/runner/boilerplate-mongomongoose-3/node_modules/mongoose/lib/index.js:1151:10)
    at Mongoose.connect (/home/runner/boilerplate-mongomongoose-3/node_modules/mongoose/lib/index.js:329:20)
    at Object.<anonymous> (/home/runner/boilerplate-mongomongoose-3/myApp.js:3:10)
    at Module._compile (internal/modules/cjs/loader.js:999:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)
(node:310) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:310) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
GET
MongooseError: Operation `people.insertOne()` buffering timed out after 10000ms
    at Timeout.<anonymous> (/home/runner/boilerplate-mongomongoose-3/node_modules/mongoose/lib/drivers/node-mongodb-native/collection.js:149:23)
    at listOnTimeout (internal/timers.js:554:17)
    at processTimers (internal/timers.js:497:7)
GET
MongooseError: Operation `people.insertOne()` buffering timed out after 10000ms
    at Timeout.<anonymous> (/home/runner/boilerplate-mongomongoose-3/node_modules/mongoose/lib/drivers/node-mongodb-native/collection.js:149:23)
    at listOnTimeout (internal/timers.js:554:17)
    at processTimers (internal/timers.js:497:7)

Here is the code of the simple.env file

MONGO_URI='mongodb+srv://mon-project-wee:monproject@monprojectwee.brqps.mongodb.net/monprojectWee?retryWrites=true&w=majority'

Don’t use a .env file, use the UI option replit provides (padlock icon in the sidebar)

1 Like

Here is a screenshot of what I did:

This de code:

require('dotenv').config();
const mongoose = require('mongoose');
mongoose.connect(process.env.MONGO_URI);

const mySecret = process.env['monprojectwee']

mongoose.connection.on("error", err => {

  console.log("err", err)

})
mongoose.connection.on("connected", (err, res) => {

  console.log("mongoose is connected")

})

let Schema = mongoose.Schema;
let personSchema = new Schema({
  name: {
    type: String,
    required: true
  },
  age: Number,
  favoriteFoods: [String]
});

let Person = mongoose.model('Person', personSchema);

var createAndSavePerson = function() {
  let person = new Person({name: 'EDOUKA EPOH WILFRID', age: 34, favoriteFoods: ['ananas', 'bananas', 'cakes']});
  person.save(function(err, data) {
    if(err){
      console.log(err)
    }else{
      console.log(data)
    }
  });  
};

const createManyPeople = (arrayOfPeople, done) => {
  done(null /*, data*/);
};

const findPeopleByName = (personName, done) => {
  done(null /*, data*/);
};

const findOneByFood = (food, done) => {
  done(null /*, data*/);
};

const findPersonById = (personId, done) => {
  done(null /*, data*/);
};

const findEditThenSave = (personId, done) => {
  const foodToAdd = "hamburger";

  done(null /*, data*/);
};

const findAndUpdate = (personName, done) => {
  const ageToSet = 20;

  done(null /*, data*/);
};

const removeById = (personId, done) => {
  done(null /*, data*/);
};

const removeManyPeople = (done) => {
  const nameToRemove = "Mary";

  done(null /*, data*/);
};

const queryChain = (done) => {
  const foodToSearch = "burrito";

  done(null /*, data*/);
};


/** **Well Done !!**
/* You completed these challenges, let's go celebrate !
 */

//----- **DO NOT EDIT BELOW THIS LINE** ----------------------------------



exports.PersonModel = Person;
exports.createAndSavePerson = createAndSavePerson;
exports.findPeopleByName = findPeopleByName;
exports.findOneByFood = findOneByFood;
exports.findPersonById = findPersonById;
exports.findEditThenSave = findEditThenSave;
exports.findAndUpdate = findAndUpdate;
exports.createManyPeople = createManyPeople;
exports.removeById = removeById;
exports.removeManyPeople = removeManyPeople;
exports.queryChain = queryChain;

Here is the error message

 npm start

> fcc-mongo-mongoose-challenges@0.0.1 start /home/runner/boilerplate-mongomongoose-3
> node server.js

Your app is listening on port 3000
(node:19185) UnhandledPromiseRejectionWarning: 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.
    at NativeConnection.Connection.openUri (/home/runner/boilerplate-mongomongoose-3/node_modules/mongoose/lib/connection.js:686:11)
    at /home/runner/boilerplate-mongomongoose-3/node_modules/mongoose/lib/index.js:330:10
    at /home/runner/boilerplate-mongomongoose-3/node_modules/mongoose/lib/helpers/promiseOrCallback.js:32:5
    at new Promise (<anonymous>)
    at promiseOrCallback (/home/runner/boilerplate-mongomongoose-3/node_modules/mongoose/lib/helpers/promiseOrCallback.js:31:10)
    at Mongoose._promiseOrCallback (/home/runner/boilerplate-mongomongoose-3/node_modules/mongoose/lib/index.js:1151:10)
    at Mongoose.connect (/home/runner/boilerplate-mongomongoose-3/node_modules/mongoose/lib/index.js:329:20)
    at Object.<anonymous> (/home/runner/boilerplate-mongomongoose-3/myApp.js:3:10)
    at Module._compile (internal/modules/cjs/loader.js:999:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)
(node:19185) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:19185) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

type or paste code here

Your connection URI may be wrong, it should look like this:

mongodb+srv://USER:PASSWORD@cluster0.udbut.mongodb.net/DATABASENAME?retryWrites=true&w=majority

What did you call your cluster? my cluster is named cluster0

Also, never share your password online like you did there, even if you think little could be done with it, it could be used to trick you into getting more info from you

Thank you for the advice you give me I did not know.
my cluster is called: monprojectWee.

Please I replace this code at what level?

mongodb + srv: // USER: PASSWORD@cluster0.udbut.mongodb.net/DATABASENAME? retryWrites = true & w = majority

On second thought, ignore what I said, just check that in here:

MONGO_URI='mongodb+srv://mon-project-wee:monproject@monprojectwee.brqps.mongodb.net/monprojectWee?retryWrites=true&w=majority'

your user is definitely: mon-project-wee
your password is correct
your cluster name is: monprojectwee
your database name is: monprojectWee

You check these things on the mongodb website, after logging in

If any of these are wrong change them. If they are all right already then the problem is not in your .env key

1 Like

Thank you I managed to connect to the database and the information is displayed.

 npm start

> fcc-mongo-mongoose-challenges@0.0.1 start /home/runner/boilerplate-mongomongoose-3
> node server.js

Your app is listening on port 3000
mongoose is connected
GET
{
  name: 'xxx',
  age: xx,
  favoriteFoods: [ 'xx', 'xx', 'xx' ],
  _id: new ObjectId("xxx"),
  __v: xx
}

Great to hear @WEEYDE

If I gave you the solution please click on ‘solution’ under my post to close the thread and help others find it :slight_smile:

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.