Unable to save a record of a Model MongoDB -HELP!

I’m failing this challenge with a Creating and saving a db item should succeed (Test timed out) message but I believe my code is correct. Any help would be appreciated.

.env (password and username removed)

MONGO_URI="mongodb+srv://<username>:<pw>@dgcluster-xgrh1.mongodb.net/test?retryWrites=true&w=majority"

package.json –

{
  "name": "fcc-mongo-mongoose-challenges",
  "version": "0.0.1",
  "description": "A boilerplate project",
  "main": "server.js",
  "scripts": {
    "start": "node server.js"
  },
  "dependencies": {
    "mongodb": "3.4.1",
    "mongoose": "5.8.5",
    "express": "^4.17.1",
    "body-parser": "^1.19.0"
  },
  "engines": {
    "node": "12.13.1"
  },
  "repository": {
    "type": "git",
    "url": "https://hyperdev.com/#!/project/welcome-project"
  },
  "keywords": [
    "node",
    "hyperdev",
    "express"
  ],
  "license": "MIT"
}

myApp.js

var mongoose = require('mongoose');
mongoose.connect('mongodb+srv://<username>:<pw>@dgcluster-xgrh1.mongodb.net/test?retryWrites=true&w=majority', {useNewUrlParser: true, useUnifiedTopology: true});

var personSchema = new mongoose.Schema({
  name: { type: String, required: true },
  age: Number,
  favoriteFoods: [String]
});
const Person = mongoose.model("Person", personSchema);

var createAndSavePerson = function(done) {
  
var dingusMan = new Person({name: "Dingus", age: 8, favoriteFoods: ["beef", "cheetbos"]});

  dingusMan.save(function(err, data) {
    if (err) return console.error(err);
    done(null, data)
  });

};

What happens…

Upon submitting my answer, the glitch project console shows a GET request, then the errors listed below appear after a brief pause;

(node:8548) UnhandledPromiseRejectionWarning: MongooseTimeoutError: Server selection timed out after 30000 ms

11:06 PM

at new MongooseTimeoutError (/rbd/pnpm-volume/539825d0-cdc8-41e7-b1d2-a3d73c12f188/node_modules/.registry.npmjs.org/mongoose/5.8.5/node_modules/mongoose/lib/error/timeout.js:22:11)

11:06 PM

at NativeConnection.Connection.openUri (/rbd/pnpm-volume/539825d0-cdc8-41e7-b1d2-a3d73c12f188/node_modules/.registry.npmjs.org/mongoose/5.8.5/node_modules/mongoose/lib/connection.js:763:19)

11:06 PM

at Mongoose.connect (/rbd/pnpm-volume/539825d0-cdc8-41e7-b1d2-a3d73c12f188/node_modules/.registry.npmjs.org/mongoose/5.8.5/node_modules/mongoose/lib/index.js:332:15)

11:06 PM

Jump Toat Object.<anonymous> (/app/myApp.js:18:10)

11:06 PM

at Module._compile (internal/modules/cjs/loader.js:759:30)

11:06 PM

at Object.Module._extensions..js (internal/modules/cjs/loader.js:770:10)

11:06 PM

at Module.load (internal/modules/cjs/loader.js:628:32)

11:06 PM

at Function.Module._load (internal/modules/cjs/loader.js:555:12)

11:06 PM

at Module.require (internal/modules/cjs/loader.js:666:19)

11:06 PM

at require (internal/modules/cjs/helpers.js:16:16)

11:06 PM

Jump Toat Object.<anonymous> (/app/server.js:61:14)

11:06 PM

at Module._compile (internal/modules/cjs/loader.js:759:30)

11:06 PM

at Object.Module._extensions..js (internal/modules/cjs/loader.js:770:10)

11:06 PM

at Module.load (internal/modules/cjs/loader.js:628:32)

11:06 PM

at Function.Module._load (internal/modules/cjs/loader.js:555:12)

11:06 PM

at Function.Module.runMain (internal/modules/cjs/loader.js:826:10)

11:06 PM

(node:8548) 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(). (rejection id: 1)

11:06 PM

(node:8548) [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 (Macintosh; Intel Mac OS X 10_15_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36.

Challenge: MongoDB and Mongoose - Create and Save a Record of a Model

Link to the challenge:
https://www.freecodecamp.org/learn/apis-and-microservices/mongodb-and-mongoose/create-and-save-a-record-of-a-model

you must use promise structure or even better use async and await in your code to handle asynchronous functions for promise based rejection .
for example in apply of mongoose.save function you can use this way:

var createAndSavePerson = async function(done) {
 
var dingusMan = new Person({name: "Dingus", age: 8, favoriteFoods: ["beef", "cheetbos"]});

 await dingusMan.save(function(err, data) {
   if (err) return console.error(err);
   done(null, data)
 });

};

or you can use promises directly:

var createAndSavePerson = function(done) {
  
var dingusMan = new Person({name: "Dingus", age: 8, favoriteFoods: ["beef", "cheetbos"]});

  dingusMan.save()
       .then(function( data) {
             done(null, data)
        })
      .catch(function(error){
          console.log(error);
      });
1 Like

Thanks for the reply. I studied up on promises and tried your code but am still having the same timeout error. I have the link to the glitch project here

I check your code is not working. here

Thanks for the replies!

Seems to be working now. myApp.js code (below) is same. I cleared cache and added a new mongodb user and updated the .env file.


const mongoose = require('mongoose');
mongoose.connect(process.env.MONGO_URI, {useNewUrlParser: true, useUnifiedTopology: true});


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

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



var createAndSavePerson = function(done) {
  var dingusMan = new Person({name: "Dingus", age: 8, favoriteFoods: ["beef", "cheetos"]});
  
  dingusMan.save(function(err, data) {
    if (err) return console.error(err);
    done(null, data)
  });

};
1 Like

if anyone comes here with problems after using the code snippet above - try adding async to your createAndSavePerson function like:

var createAndSavePerson = async function(done) { ....