Exercise Tracker - Cannot connect to Mongo Atlas

Tell us what’s happening:

I cannot insert a user in my database. I don’t understand why. I’m doing the exact same things I did for the URL shortener, and nothing happens. I’ve inserted the connect uri in the environment variable MONGO_URI.

Your code so far

const mongoose = require("mongoose");

const UserSchema = new mongoose.Schema({
  username: String

const User = mongoose.model("User", UserSchema);

app.get("/test1", function(req, res) {
  const usertest = new User({ username: "usertest1" });
  res.send("Test 1 executed.");

As I said, nothing happens. In the logs, I get a deprecation warning:

(node:17818) DeprecationWarning: `open()` is deprecated in mongoose >= 4.11.0, use `openUri()` instead, or set the `useMongoClient` option if using `connect()` or `createConnection()`. See http://mongoosejs.com/docs/4.x/docs/connections.html#use-mongo-client

I’ve tried adding changing the connect command as suggested by the deprecation link like this:

mongoose.connect(process.env.MONGO_URI, {useMongoClient: true});

But it invalidates the connection URI that I get from Atlas, so I dropped it. Apart from this, I don’t know what else to do. Any help is appreciated. I should add that if on the ‘test1’ get request I do res.send(usertest);, I can see the user object with the ID. But it doesn’t seem to get sent to the database.

Challenge: Exercise Tracker

Link to the challenge:

I have had a similar problem before

  1. Try to check whether you are really connected to the database by adding a call back to mongoose.connect.
mongoose.connect(process.env.MONGO_URI, ()  => console.log('Connected to DB')
  1. For my case i had multiple clusters and was using the wrong key:
    By default if you are using free version of mongoDB, the database is named test. Go to the cluster whose key you are using, check whether a database named test has been created in the cluster. If it is not there then you have not connected to the database at all. Create a database, name it test and then inside the database create a collection called users . Try connecting again.
  2. It is also possible you made a mistake in the database key. Cross check as well.
  3. Also try using the most recent version of dependencies. I was getting lots of warning when doing the projects only to realise i had to update to the most recent version.
1 Like

I wrote you a reply but I think it wasn’t sent. Anyway, updating the packages did the trick. Thank you!

1 Like