MongoDB and Mongoose - Install and Set Up Mongoose

MongoDB and Mongoose - Install and Set Up Mongoose
0
#16

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.

#17

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

#18

@ 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:[email protected]<PORT>.mlab.com:<PORT>/<DATABASE-NAME>

#19

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

#20

@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:
https://learn.freecodecamp.org/apis-and-microservices/mongodb-and-mongoose

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
#21

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

#22

Glad to hear it.

Good luck.

1 Like
#23

Has anybody tried this recently? I can’t connect to Mongoose. Getting the following error:
(node:14936) UnhandledPromiseRejectionWarning: MongoNetworkError: connection 3 to fcc-shard-00-00-vcnna.mongodb.net:27017 closed

It passes the first 2 tests which are that mongodb and mongoose are in the dependencies. Also, the instructions are outdated, as mlab is now mongodb Atlas and the current uri looks like this:

mongodb+srv://mscanza:[email protected]/test?retryWrites=true

Could this be why it is not able to connect to Mongoose?

#24

FCC: mlab is no longer accepting new users. Does this mean these challenges can no longer be completed? Can you please look into this?

1 Like
#25

#26

@mscanza, I’ll do a test run later this evening, if no one hasn’t got to it by then…

#27

im having the same issue as user @mscanza. That you have to use Mongo Atlas meaning i can’t follow the instructions in the challenge. Does anyone know when the (apis-and-microservices) challenges will be updated or a quick fix to be able to complete the challenge? Thank you.

#28

I have just confirmed that the lessons still work even after the changes made from the acquisition of mlab by mongodb, these instructions need to be fully changed however, I will look to submitting a PR or see if one hasn’t already been submitted.

But, it should not stop anyone from continuing with the lessons, since the instructions in MongoDB Atlas are pretty clear, see below for brief instructions or go to this link for a more detailed set of instructions from a PR of the lesson that is pending approval.

  1. Create your MongoDB Atlas account.
  2. As soon as you login, it will walk you through building your first cluster - may take a few minutes to complete.
  3. Then following the green tab in the bottom left of the screen, click on Create your first database user, follow the instructions and create a user with a password.
  4. In the same green Get started tab click on Whitelist your IP address, warning here, glitch will not connect if you don’t allow all IP addresses, which is what I did for it to work.
  5. Click Connect to Your Cluster > click connect in the sandbox window, and then click connect your application in the pop up window, then copy the connection string, and paste it in your .env file in glitch and substitute the password you provided in step 3 for the <password> area , and you are good to go. Test the first lesson and it should pass.

Update
mongoDB Atlas says it requires MongoDB version 4.0 for the free tier clusters . If you are using Mongoose, this means that you would need mongoose > 5.2 to have a compatible mongoDB driver that Atlas can use

Submit the link to your LIVE page from glitch for the challenge to pass and not the link to your glitch editor

9 Likes
Install and Set Up Mongoose - Won't connect to database
mongoDB and glitch (URL shortener)
MongoDB and Mongoose - Mongoose is not connected
2MongoDB and Mongoose - Install and Set Up Mongoose need HELP!
MongoDB and Mongoose - Install and Set Up Mongoose-error
How to continue with Apis and Microservices's MongoDB and Mongoose challenges now that mlab doesn't accept any registrations?
#29

Thank you Dereje1 this was extremely helpful. Whitelisting all ip addresses fixed it.

#30

Hi Team,

I cannot establish connection to database.
My code:
.env file
Screenshot%20from%202019-03-14%2018-52-12

myApp.js
var mongodb = require(‘mongodb’);
const mongoose = require(‘mongoose’);
mongoose.connect(process.env.MONGO_URI,{useNewUrlParser: true});

package.json

{
“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.4”,
“body-parser”: “^1.18.3”,
“mongoose”: “^5.4.19”,
“mongodb”: “^3.1.17”
},
“engines”: {
“node”: “4.4.5”
},
“repository”: {
“type”: “git”,
“url”: "
},
“keywords”: [
“node”,
“hyperdev”,
“express”
],
“license”: “MIT”
}
Please help!!!

#31

My console output

#32

I forgot to mention. I’m on Ubuntu 16.04.

#33

see here first: MongoDB and Mongoose - Install and Set Up Mongoose

1 Like
#34

Thanks for the reference Dereje1. I’m a little bit confused here. I tried to change dependencies version and it did not work out. If you know the trick, please tell…

#35

Did you whitelist all ip addresses in MongoDB atlas as pointed out in the link I gave you ?
If you followed the instructions I posted above and still can’t get it to work post your glitch link and i’ll look into it