Can't get the MongoDB / Mongoose - Connection to work

Tell us what’s happening:
I have tried to solve what the task is. I even compared with the solution page. But I could not get the JSON data to be stored in the MongoDB. There seems to be some sort of connection error. I had my myApp.js run smoothly and only throw an error, when the tests on freeCodeCamp were initiated.

I now have bluntly copied over the solution from the solution page. But it still does not work. I am stuck. I must oversee something simple. But I am probably too close. I have started watching YouTube-tutorials about MongoDB and Mongoose. But so far they all started, where the connection already was there. I could not resolve my problem. Can you help?

Your code so far
https://repl.it/join/xgzbxgas-mseibert

.env

MONGO_URI='mongodb://localhost/my_database'

myApp.js

/** 1) Install & Set up mongoose */

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

/** 2) Create a 'Person' Model */
var personSchema = new mongoose.Schema({
  name: String,
  age: Number,
  favoriteFoods: [String]
});

/** 3) Create and Save a Person */
var Person = mongoose.model('Person', personSchema);

var createAndSavePerson = function(done) {
  var janeFonda = new Person({name: "Jane Fonda", age: 84, favoriteFoods: ["eggs", "fish", "fresh fruit"]});

  janeFonda.save(function(err, data) {
    if (err) return console.error(err);
    done(null, 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;

The error I get:

node:130) Warning: Accessing non-existent property ‘MongoError’ of module exports inside circular dependency
(Use node --trace-warnings ... to show where the warning was created)
(node:130) DeprecationWarning: current URL string parser is deprecated, and will be removed in a future version. To use the new parser, pass option { useNewUrlParser: true } to MongoClient.connect.
(node:130) DeprecationWarning: current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.
Your app is listening on port 3000
(node:130) UnhandledPromiseRejectionWarning: MongoNetworkError: failed to connect to server [localhost:27017] on first connect [Error: connect ECONNREFUSED 127.0.0.1:27017
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1146:16) {
name: ‘MongoNetworkError’
}]
at Pool. (/home/runner/boilerplate-mongomongoose/node_modules/mongodb/lib/core/topologies/server.js:438:11)
at Pool.emit (events.js:315:20)
at /home/runner/boilerplate-mongomongoose/node_modules/mongodb/lib/core/connection/pool.js:562:14
at /home/runner/boilerplate-mongomongoose/node_modules/mongodb/lib/core/connection/pool.js:995:11
at /home/runner/boilerplate-mongomongoose/node_modules/mongodb/lib/core/connection/connect.js:32:7
at callback (/home/runner/boilerplate-mongomongoose/node_modules/mongodb/lib/core/connection/connect.js:280:5)
at Socket. (/home/runner/boilerplate-mongomongoose/node_modules/mongodb/lib/core/connection/connect.js:310:7)
at Object.onceWrapper (events.js:422:26)
at Socket.emit (events.js:315:20)
at emitErrorNT (internal/streams/destroy.js:106:8)
at emitErrorCloseNT (internal/streams/destroy.js:74:3)
at processTicksAndRejections (internal/process/task_queues.js:80:21)
(node:130) 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 Command-line API | Node.js v21.2.0 Documentation). (rejection id: 1)
(node:130) [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.

Your browser information:

User Agent is: Mozilla/5.0 (X11; CrOS x86_64 13597.94.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.186 Safari/537.36.

Challenge: Create and Save a Record of a Model

Link to the challenge:

Hello @mseibert, the error is a bit cryptic so mine is a wild shot but: have you created the Mongo DB cluster? If so, is it working properly?

I think FCC suggest MongoAtlas, usually the db uri connection string looks like:

mongodb+srv://<username>:<password>@<cluster-name>.mongodb.net/<db-name>?retryWrites=true&w=majority

Or in other words: are you sure your db

MONGO_URI=‘mongodb://localhost/my_database’

is running and open to connections?

Hope it helps :slight_smile:


edit: this is the relevant error part that matters:

As you can see the connection is refused hence throwing the error

1 Like

No, it’s again a little weird. I thought that the Mongoose-Framework would build some sort of a test account. That actually helps. I will do that and try again.

Mongoose purpose is to let you use standard JS -like syntax to work with Mongo, so you can use a familiar syntax instead of writing mongo queries.

All the rest is up to you :slight_smile:

1 Like
  1. make sure that mongodb is installed properly on your machine. If not you can use mongodb atlas.
  2. To remove deprecation warnings us this code. make sure you provide process.env variables for MONGO_URI and DB_NAME
mongoose.connect(process.env.MONGO_URI, {
        dbName: process.env.DB_NAME,
        useNewUrlParser: true,
        useUnifiedTopology: true,
        useFindAndModify: false,
        useCreateIndex: true,
    }).then(()=>{
        console.log('database connected.')
    }).catch((err) => console.log(err.message))

source link= https://mongoosejs.com/docs/deprecations.html

1 Like

@usama.khalid @Marmiz Thanks for all of you. Created a cloud database with MongoDB Atlas. Now everything works and I could pass the test.

This individual help is very valuable for me. You rock!

1 Like

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