MongoDB and Mongoose - Install and Set Up Mongoose

Hi! I’m doing the first exercise from the “Mongo DB and Mongoose” section, but Glitch trows me the error " Error: Cannot find module ‘mongoose’ ".
My code for the dependencies on package.json is:
[…]
“dependencies”: {
“express”: “^4.16.3”,
“body-parser”: “^1.18.3”,
“mongoose”: “^5.1.6”,
“mongodb”: “^3.4.13”
},
[…]

And the code on MyApp,js:
[…]
const mongoose = require(‘mongoose’);
mongoose.connect(process.env.MONGO_URI);
[…]

Any idea of what is wrong?

2 Likes

Hi!

I tried your code and cannot replicate the error. May you post all the code?

The complete code of package.json is

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

The only thing I add to myApp.js is

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

The rest of the code in that file is the Glitch code that was there when I open the project from the FreeCodeCamp section.

The code in .env is

SECRET=
MADE_WITH=
MONGO_URI=mongodb://XXXX:XXXX@ds249818.mlab.com:49818/pruebabeloqui

where the Xs are the user and password of the database.

1 Like

According to your error ,node is not abale to find the mongoose module so you can try this .

  1. First check whether you have multiple version or not . Sometime problem occur due to that .
  2. Re install all module for the project .

Then check in node shell for the mongoose .

1 Like

I changed my dependencies to

"mongoose": "^5.1.6",
"mongodb": "^3.0.10"

and now it works. Thank you!

5 Likes

I had a problem in that my password used a key that wasn’t supported in the .env file. That character was one of these = !@#$%^&*()

To solve it, I made another user, set the password to not contain one of the above symbols and then deleted the old user. When I just used numbers and letters in my username and password, I passed the tests.

Hope this helps! :smiley:

9 Likes

It also looks like you can’t use colons in your password, either. So can we only use letters and numbers?

EDIT: You can also use underscores…

It’s helpful, thank.

    "mongodb": "*",
    "mongoose": "*"
1 Like

I know this post is old, but I had a similar problem and a similar fix. It seems that this exercise will not work with the current version of MongoDB. It has to be < version 4.0.

4 Likes

Thanks for this post. That helped. I had the same some special charater in the password :stuck_out_tongue:

can uh tell me that why you have declared mongoose as const

to call the connect method of the mongoose we need to require the mongoose module and put it in a const.

Thanks, I was also running into the same issue. My password had the “@” in it.

Howdy, @Priyanka29!

I don’t know if you ever got an answer to your question, but if you’re still interested, I believe the const is used in require statements to prevent the variable from changing. It locks the variable mongoose into always representing the middleware. It doesn’t have to be a const. You could also use var or let. I also like to assign all of my require middleware to constants.

hiii i done everything all right but when i upload on freecodecamp i get
// running tests
Not Found
Not Found
Not Found
// tests completed

i change only this code
const mongoose = require('mongoose'); mongoose.connect(process.env.MONGO_URI);

and i also add mongodb and mongoose package

@ critter

Did you…

  1. Add mongodb and mongoose to the project’s package.json? (required)
  2. Store your mLab database URI in the private .env file as MONGO_URI? (required)

You should have in your .env file something like MONGO_URI=mongodb://dbuser:dbpassword@ds0<PORT>.mlab.com:<PORT>/<DATABASE-NAME>

yes I stored in package.json "mongodb": "^3.1.11", "mongoose": "^5.4.11", and i also set url in .env file

var express = require('express');
var app = express();
var bodyParser = require('body-parser');
const mongoose = require('mongoose');
mongoose.connect(process.env.MONGO_URI);
const path = require('path')

// --> 7)  Mount the Logger middleware here
app.use((req, res, next) => {
console.log(req.method + ' ' + req.path + ' ' + '-' + ' ' + req.ip)
next()
})

// --> 11)  Mount the body-parser middleware  here
app.use( bodyParser.json() );       // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({     // to support URL-encoded bodies
  extended: true
})); 

/** 1) Meet the node console. */
app.use('*', (req, res, next) => {
console.log('Hello World')
next()
})

/** 2) A first working Express Server */
//app.get('/', function (req, res) {
//  res.send('Hello Express')
//})

/** 3) Serve an HTML file */
app.get('/', (req, res) => {
  res.sendFile(path.join(__dirname, './views/index.html'))
})

/** 4) Serve static assets  */
app.use('/', express.static(path.join(__dirname, 'public')))

/** 5) serve JSON on a specific route */
app.get('/json', (req, res) => {
  let message = 'Hello json'
  if (process.env.MESSAGE_STYLE === 'uppercase') {
    return res.json({"message": message.toUpperCase()})
  }
  return res.status(200).json({"message": message})
})

/** 6) Use the .env file to configure the app */
 var message ="Hello json";
var msgObj ={};
msgObj = {"message":message};
    if(process.env.MESSAGE_STYLE=="uppercase")
    {
      message = message.toUpperCase();
      msgObj.message = message;
    }
      
    app.get("/json", function(req, res) {
      return res.json(msgObj);
      });
 
/** 7) Root-level Middleware - A logger */
//  place it before all the routes !


/** 8) Chaining middleware. A Time server */
app.get('/now', (req, res, next) => {
  req.time = new Date().toISOString()
 
  next()
}, (req, res) => {
  res.status(200).json({"time": req.time})
})

/** 9)  Get input from client - Route parameters */
app.get('/:word/echo', (req, res) => {
  res.status(200).json({"echo": req.params.word})
})

/** 10) Get input from client - Query parameters */
//
// /name?first=<firstname>&last=<lastname>
app.route('/name').get((req, res) => {
  res.status(200).json({"name": req.query.first + ' ' + req.query.last})
   
}).post((req, res) => {
  res.status(200).json({"name": req.query.first + ' ' + req.query.last})
})
  
/** 11) Get ready for POST Requests - the `body-parser` */
// place it before all the routes !


/** 12) Get data form POST  */
app.post('/name', (req, res) => {
  let name = req.body.first + ' ' + req.body.last;
  res.json({name: 'firstname lastname'});
});


// This would be part of the basic setup of an Express app
// but to allow FCC to run tests, the server is already active
/** app.listen(process.env.PORT || 3000 ); */

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

 module.exports = app;

and package.json

{
  "//1": "describes your app and its dependencies",
  "//2": "https://docs.npmjs.com/files/package.json",
  "//3": "updating this file will download and update your packages",
  "name": "hello-express",
  "version": "0.0.1",
  "description": "A simple Node app built on Express, instantly up and running.",
  "main": "server.js",
  "scripts": {
    "start": "node server.js"
  },
  "dependencies": {
    "express": "^4.16.4",
    "fcc-express-bground": "https://github.com/Em-Ant/fcc-express-bground-pkg.git",
    "mongodb": "^3.1.11",
    "mongoose": "^5.4.11",
    "connect-mongo": "^2.0.3"
  },
  "engines": {
    "node": "8.x"
  },
  "repository": {
    "url": "https://glitch.com/edit/#!/hello-express"
  },
  "license": "MIT",
  "keywords": [
    "node",
    "glitch",
    "express"
  ]
}
var bGround = require('fcc-express-bground');
var myApp = require('./myApp');
var express = require('express');
var app = express();

if (!process.env.DISABLE_XORIGIN) {
  app.use(function(req, res, next) {
    var allowedOrigins = ['https://narrow-plane.gomix.me', 'https://www.freecodecamp.com'];
    var origin = req.headers.origin || '*';
    if(!process.env.XORIG_RESTRICT || allowedOrigins.indexOf(origin) > -1){
         console.log(origin);
         res.setHeader('Access-Control-Allow-Origin', origin);
         res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    }
    next();
  });
}
app.use(express.static(__dirname + 'public'));
app.use(express.static(__dirname + 'views'));
var port = process.env.PORT || 3000;
bGround.setupBackgroundApp(app, myApp, __dirname).listen(port, function(){
  bGround.log('Node is listening on port '+ port + '...')
});

and also server.js

@critter

Ok, so you’re still editing the Node and Express Challenges files. You need to start a new project with a different set of files for the MongoDB and Mongoose challenges.

Go here:

And open the new project by clicking on this link

Start this project on Glitch using this link or clone this repository on GitHub! If you use Glitch, remember to save the link to your project somewhere safe!

Use mLab to host a free mongodb instance for your projects

For the following challenges, we are going to start using MongoDB to store our data. To simplify the configuration, we are going to use mLab.

2 Likes

thanks, buddy it works properly the issue is same that you told