MongoDB and Mongoose - Install and Set Up Mongoose-error

MongoDB and Mongoose - Install and Set Up Mongoose-error
0

error: timeout has occured

{{
  "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.0.10"
  },
  "engines": {
    "node": "4.4.5"
  },
  "repository": {
    "type": "git",
    "url": "https://hyperdev.com/#!/project/welcome-project"
  },
  "keywords": [
    "node",
    "hyperdev",
    "express"
  ],
  "license": "MIT"
}
 module.exports = app;
const mongoose = require('mongoose');
mongoose.connect(process.env.MONGO_URI);

First, take a look below and ensure that you have followed all the steps, if you still are not able to connect, then please state the specific issues/errors in that thread,

I have been having issues with this since the beginning of the month. I’ve followed the updated instructions but still get the following errors:

// running tests
Unexpected token < in JSON at position 0
mongoose is not connected
Unexpected token < in JSON at position 0
// tests completed

I have used my original mlabs account from before MongoDB acquired them. I have also tried creating a brand new MongoDB Atlas account. Neither of them will pass the test.

I have remixed the glitch app as well as cloned it from GitHub.

I have checked to make sure that all IP addresses are white listed:

I have double and triple checked that I have the proper DB connection string.

I am at a total loss as to why it is not working.

My app.js:

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

My 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.12.4",
    "body-parser": "^1.15.2",
    "mongoose": "^5.1.6",
    "mongodb": "^3.0.10"
  },
  "engines": {
    "node": "4.4.5"
  },
  "repository": {
    "type": "git",
    "url": "https://hyperdev.com/#!/project/welcome-project"
  },
  "keywords": [
    "node",
    "hyperdev",
    "express"
  ],
  "license": "MIT"
}

my .env:

SECRET=
MONGO_URI=mongodb+srv://chrisjohnson1:[email protected]/test?retry

my glitch url:

Your app works fine and passes the challenge for me when I use my own working connection string with it, your connection string seems strange, it should look like the below except the asterisks, you should only change the password in the string you copy from mongodbAtlas

mongodb+srv://admin:******@cluster0-gtlth.mongodb.net/test?retryWrites=true

Also, the solution you submit should be the live page of glitch and not the editor

1 Like

i still get an error that says mongoose is not connected


/**********************************************
* 3. FCC Mongo & Mongoose Challenges
* ==================================
***********************************************/

/** # MONGOOSE SETUP #
/*  ================== */

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

// Add `mongodb` and `mongoose` to the project's `package.json`. Then require 
// `mongoose`. Store your **mLab** database URI in the private `.env` file 
// as `MONGO_URI`. Connect to the database using `mongoose.connect(<Your URI>)`

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


/** # SCHEMAS and MODELS #
/*  ====================== */

/** 2) Create a 'Person' Model */

// First of all we need a **Schema**. Each schema maps to a MongoDB collection
// and defines the shape of the documents within that collection. Schemas are
// building block for Models. They can be nested to create complex models,
// but in this case we'll keep things simple. A model allows you to create
// instances of your objects, called **documents**.

// Create a person having this prototype :

// - Person Prototype -
// --------------------
// name : string [required]
// age :  number
// favoriteFoods : array of strings (*)

// Use the mongoose basic *schema types*. If you want you can also add more
// fields, use simple validators like `required` or `unique`, and set
// `default` values. See the [mongoose docs](http://mongoosejs.com/docs/guide.html).

// <Your code here >
var Schema = mongoose.Schema;

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

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

// **Note**: GoMix is a real server, and in real servers interactions with
// the db are placed in handler functions, to be called when some event happens
// (e.g. someone hits an endpoint on your API). We'll follow the same approach
// in these exercises. The `done()` function is a callback that tells us that
// we can proceed after completing an asynchronous operation such as inserting,
// searching, updating or deleting. It's following the Node convention and
// should be called as `done(null, data)` on success, or `done(err)` on error.
// **Warning** - When interacting with remote services, **errors may occur** !

// - Example -
// var someFunc = function(done) {
//   ... do something (risky) ...
//   if(error) return done(error);
//   done(null, result);
// };

/** # [C]RUD part I - CREATE #
/*  ========================== */

/** 3) Create and Save a Person */

// Create a `document` instance using the `Person` constructor you build before.
// Pass to the constructor an object having the fields `name`, `age`,
// and `favoriteFoods`. Their types must be conformant to the ones in
// the Person `Schema`. Then call the method `document.save()` on the returned
// document instance, passing to it a callback using the Node convention.
// This is a common pattern, all the **CRUD** methods take a callback 
// function like this as the last argument.

// - Example -
// ...
// person.save(function(err, data) {
//    ...do your stuff here...
// });

var createAndSavePerson = function(done) {
  
  done(null /*, data*/);

};

/** 4) Create many People with `Model.create()` */

// Sometimes you need to create many Instances of your Models,
// e.g. when seeding a database with initial data. `Model.create()`
// takes an array of objects like [{name: 'John', ...}, {...}, ...],
// as the 1st argument, and saves them all in the db.
// Create many people using `Model.create()`, using the function argument
// 'arrayOfPeople'.

var createManyPeople = function(arrayOfPeople, done) {
    
    done(null/*, data*/);
    
};

/** # C[R]UD part II - READ #
/*  ========================= */

/** 5) Use `Model.find()` */

// Find all the people having a given name, using `Model.find() -> [Person]`
// In its simplest usage, `Model.find()` accepts a **query** document (a JSON
// object ) as the first argument, and returns an **array** of matches.
// It supports an extremely wide range of search options. Check it in the docs.
// Use the function argument `personName` as search key.

var findPeopleByName = function(personName, done) {
  
  done(null/*, data*/);

};

/** 6) Use `Model.findOne()` */

// `Model.findOne()` behaves like `.find()`, but it returns **only one**
// document, even if there are more. It is especially useful
// when searching by properties that you have declared as unique.
// Find just one person which has a certain food in her favorites,
// using `Model.findOne() -> Person`. Use the function
// argument `food` as search key

var findOneByFood = function(food, done) {

  done(null/*, data*/);
  
};

/** 7) Use `Model.findById()` */

// When saving a document, mongodb automatically add the field `_id`,
// and set it to a unique alphanumeric key. Searching by `_id` is an
// extremely frequent operation, so `moongose` provides a dedicated
// method for it. Find the (only!!) person having a certain Id,
// using `Model.findById() -> Person`.
// Use the function argument 'personId' as search key.

var findPersonById = function(personId, done) {
  
  done(null/*, data*/);
  
};

/** # CR[U]D part III - UPDATE # 
/*  ============================ */

/** 8) Classic Update : Find, Edit then Save */

// In the good old days this was what you needed to do if you wanted to edit
// a document and be able to use it somehow e.g. sending it back in a server
// response. Mongoose has a dedicated updating method : `Model.update()`,
// which is directly binded to the low-level mongo driver.
// It can bulk edit many documents matching certain criteria, but it doesn't
// pass the edited document to its callback, only a 'status' message.
// Furthermore it makes validation difficult, because it just
// direcly calls the mongodb driver.

// Find a person by Id ( use any of the above methods ) with the parameter
// `personId` as search key. Add "hamburger" to the list of her `favoriteFoods`
// (you can use Array.push()). Then - **inside the find callback** - `.save()`
// the updated `Person`.

// [*] Hint: This may be tricky if in your `Schema` you declared
// `favoriteFoods` as an `Array` without specifying the type (i.e. `[String]`).
// In that case `favoriteFoods` defaults to `Mixed` type, and you have to
// manually mark it as edited using `document.markModified('edited-field')`
// (http://mongoosejs.com/docs/schematypes.html - #Mixed )

var findEditThenSave = function(personId, done) {
  var foodToAdd = 'hamburger';
  
  done(null/*, data*/);
};

/** 9) New Update : Use `findOneAndUpdate()` */

// Recent versions of `mongoose` have methods to simplify documents updating.
// Some more advanced features (i.e. pre/post hooks, validation) beahve
// differently with this approach, so the 'Classic' method is still useful in
// many situations. `findByIdAndUpdate()` can be used when searching by Id.
//
// Find a person by `name` and set her age to `20`. Use the function parameter
// `personName` as search key.
//
// Hint: We want you to return the **updated** document. In order to do that
// you need to pass the options document `{ new: true }` as the 3rd argument
// to `findOneAndUpdate()`. By default the method
// passes the unmodified object to its callback.

var findAndUpdate = function(personName, done) {
  var ageToSet = 20;

  done(null/*, data*/);
};

/** # CRU[D] part IV - DELETE #
/*  =========================== */

/** 10) Delete one Person */

// Delete one person by her `_id`. You should use one of the methods
// `findByIdAndRemove()` or `findOneAndRemove()`. They are similar to the
// previous update methods. They pass the removed document to the cb.
// As usual, use the function argument `personId` as search key.

var removeById = function(personId, done) {
  
  done(null/*, data*/);
    
};

/** 11) Delete many People */

// `Model.remove()` is useful to delete all the documents matching given criteria.
// Delete all the people whose name is "Mary", using `Model.remove()`.
// Pass to it a query ducument with the "name" field set, and of course a callback.
//
// Note: `Model.remove()` doesn't return the removed document, but a document
// containing the outcome of the operation, and the number of items affected.
// Don't forget to pass it to the `done()` callback, since we use it in tests.

var removeManyPeople = function(done) {
  var nameToRemove = "Mary";

  done(null/*, data*/);
};

/** # C[R]UD part V -  More about Queries # 
/*  ======================================= */

/** 12) Chain Query helpers */

// If you don't pass the `callback` as the last argument to `Model.find()`
// (or to the other similar search methods introduced before), the query is
// not executed, and can even be stored in a variable for later use.
// This kind of object enables you to build up a query using chaining syntax.
// The actual db search is executed when you finally chain
// the method `.exec()`, passing your callback to it.
// There are many query helpers, here we'll use the most 'famous' ones.

// Find people who like "burrito". Sort them alphabetically by name,
// Limit the results to two documents, and hide their age.
// Chain `.find()`, `.sort()`, `.limit()`, `.select()`, and then `.exec()`,
// passing the `done(err, data)` callback to it.

var queryChain = function(done) {
  var foodToSearch = "burrito";
  
  done(null/*, data*/);
};

/** **Well Done !!**
/* You completed these challenges, let's go celebrate !
 */

/** # Further Readings... #
/*  ======================= */
// If you are eager to learn and want to go deeper, You may look at :
// * Indexes ( very important for query efficiency ),
// * Pre/Post hooks,
// * Validation,
// * Schema Virtuals and  Model, Static, and Instance methods,
// * and much more in the [mongoose docs](http://mongoosejs.com/docs/)


//----- **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;

​


{
  "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.20",
    "mongodb": "^3.1.11"
  },
  "engines": {
    "node": "4.4.5"
  },
  "repository": {
    "type": "git",
    "url": "https://hyperdev.com/#!/project/welcome-project"
  },
  "keywords": [
    "node",
    "hyperdev",
    "express"
  ],
  "license": "MIT"
}
/********************************************
 * DO NOT EDIT THIS FILE
 * the verification process may break
 *******************************************/

var express = require('express');
var app = express();
try{
  var mongoose = require('mongoose');
} catch (e) {
  console.log(e);
}
var fs = require('fs');
var path = require('path');
var bodyParser = require('body-parser');
var router = express.Router();

var enableCORS = function(req, res, next) {
  if (!process.env.DISABLE_XORIGIN) {
    var allowedOrigins = ['https://marsh-glazer.gomix.me','https://narrow-plane.gomix.me', 'https://www.freecodecamp.com'];
    var origin = req.headers.origin;
    if(!process.env.XORIGIN_RESTRICT || allowedOrigins.indexOf(origin) > -1) {
      console.log(req.method);
      res.set({
        "Access-Control-Allow-Origin" : origin,
        "Access-Control-Allow-Methods" : "GET, POST, OPTIONS",
        "Access-Control-Allow-Headers" : "Origin, X-Requested-With, Content-Type, Accept"
      });
    }
  }
  next();
};

// global setting for safety timeouts to handle possible
// wrong callbacks that will never be called
var timeout = 10000;

app.use(bodyParser.urlencoded({extended: 'false'}));
app.use(bodyParser.json());

app.get('/', function(req, res) {
  res.sendFile(path.join(__dirname, 'views', 'index.html'));
});

router.get('/file/*?', function(req, res, next) {
  if(req.params[0] === '.env') { return next({status: 401, message: 'ACCESS DENIED'}) }
  fs.readFile(path.join(__dirname, req.params[0]), function(err, data){
    if(err) { return next(err) }
    res.type('txt').send(data.toString());
  });
});

router.get('/is-mongoose-ok', function(req, res) {
  if (mongoose) {
    res.json({isMongooseOk: !!mongoose.connection.readyState})
  } else {
    res.json({isMongooseOk: false})
  }
});

var Person = require('./myApp.js').PersonModel;

router.use(function(req, res, next) {
  if(req.method !== 'OPTIONS' && Person.modelName !== 'Person') {
    return next({message: 'Person Model is not correct'});
  }
  next();
});

router.post('/mongoose-model', function(req, res, next) {
  // try to create a new instance based on their model
  // verify it's correctly defined in some way
  var p;
  p = new Person(req.body);
  res.json(p);
});

var createPerson = require('./myApp.js').createAndSavePerson;
router.get('/create-and-save-person', function(req, res, next) {
  // in case of incorrect function use wait timeout then respond
  var t = setTimeout(() => { next({message: 'timeout'}) }, timeout);
  createPerson(function(err, data) {
    clearTimeout(t);
    if(err) { return (next(err)); }
    if(!data) {
      console.log('Missing `done()` argument');
      return next({message: 'Missing callback argument'});
    }
     Person.findById(data._id, function(err, pers) {
       if(err) { return (next(err)); }
       res.json(pers);
       pers.remove();
     });
  });
});

var createPeople = require('./myApp.js').createManyPeople;
router.post('/create-many-people', function(req, res, next) {
  Person.remove({}, function(err) {
    if(err) { return (next(err)); }
    // in case of incorrect function use wait timeout then respond
    var t = setTimeout(() => { next({message: 'timeout'}) }, timeout);
    createPeople(req.body, function(err, data) {
      clearTimeout(t);
      if(err) { return (next(err)); }
      if(!data) {
        console.log('Missing `done()` argument');
        return next({message: 'Missing callback argument'});
      }
       Person.find({}, function(err, pers){
         if(err) { return (next(err)); }
         res.json(pers);
         Person.remove().exec();
       });
    });
  });
});

var findByName = require('./myApp.js').findPeopleByName;
router.post('/find-all-by-name', function(req, res, next) {
  var t = setTimeout(() => { next({message: 'timeout'}) }, timeout);
  Person.create(req.body, function(err, pers) {
    if(err) { return next(err) }
    findByName(pers.name, function(err, data) {
      clearTimeout(t);
      if(err) { return next(err) }
      if(!data) {
        console.log('Missing `done()` argument');
        return next({message: 'Missing callback argument'});
      }
      res.json(data);
      Person.remove().exec();
    });
  });
});

var findByFood = require('./myApp.js').findOneByFood;
router.post('/find-one-by-food', function(req, res, next) {
  var t = setTimeout(() => { next({message: 'timeout'}) }, timeout);
  var p = new Person(req.body);
  p.save(function(err, pers) {
    if(err) { return next(err) }
    findByFood(pers.favoriteFoods[0], function(err, data) {
      clearTimeout(t);
      if(err) { return next(err) }
      if(!data) {
        console.log('Missing `done()` argument');
        return next({message: 'Missing callback argument'});
      }
      res.json(data);
      p.remove();
    });
  });
});

var findById = require('./myApp.js').findPersonById;
router.get('/find-by-id', function(req, res, next) {
  var t = setTimeout(() => { next({message: 'timeout'}) }, timeout);
  var p = new Person({name: 'test', age: 0, favoriteFoods: ['none']});
  p.save(function(err, pers) {
    if(err) { return next(err) }
    findById(pers._id, function(err, data) {
      clearTimeout(t);
      if(err) { return next(err) }
      if(!data) {
        console.log('Missing `done()` argument');
        return next({message: 'Missing callback argument'});
      }
      res.json(data);
      p.remove();
    });
  });
});

var findEdit = require('./myApp.js').findEditThenSave;
router.post('/find-edit-save', function(req, res, next) {
  var t = setTimeout(() => { next({message: 'timeout'}) }, timeout);
  var p = new Person(req.body);
  p.save(function(err, pers) {
    if(err) { return next(err) }
    try {
      findEdit(pers._id, function(err, data) {
        clearTimeout(t);
        if(err) { return next(err) }
        if(!data) {
          console.log('Missing `done()` argument');
          return next({message: 'Missing callback argument'});
        }
        res.json(data);
        p.remove();
      });
    } catch (e) {
      console.log(e);
      return next(e);
    }
  });
});

var update = require('./myApp.js').findAndUpdate;
router.post('/find-one-update', function(req, res, next) {
  var t = setTimeout(() => { next({message: 'timeout'}) }, timeout);
  var p = new Person(req.body);
  p.save(function(err, pers) {
    if(err) { return next(err) }
    try {
      update(pers.name, function(err, data) {
        clearTimeout(t);
        if(err) { return next(err) }
        if (!data) {
          console.log('Missing `done()` argument');
          return next({ message: 'Missing callback argument' });
        }
        res.json(data);
        p.remove();
      });
    } catch (e) {
      console.log(e);
      return next(e);
    }
  });
});

var removeOne = require('./myApp.js').removeById;
router.post('/remove-one-person', function(req, res, next) {
  Person.remove({}, function(err) {
    if(err) if(err) { return next(err) }
    var t = setTimeout(() => { next({message: 'timeout'}) }, timeout);
    var p = new Person(req.body);
    p.save(function(err, pers) {
      if(err) { return next(err) }
      try {
        removeOne(pers._id, function(err, data) {
          clearTimeout(t);
          if(err) { return next(err) }
          if(!data) {
            console.log('Missing `done()` argument');
            return next({message: 'Missing callback argument'});
          }
          console.log(data)
          Person.count(function(err, cnt) {
            if(err) { return next(err) }
            data = data.toObject();
            data.count = cnt;
            console.log(data)
            res.json(data);
          })
        });
      } catch (e) {
        console.log(e);
        return next(e);
      }
    });
  });
});

var removeMany = require('./myApp.js').removeManyPeople;
router.post('/remove-many-people', function(req, res, next) {
  Person.remove({}, function(err) {
    if(err) { return next(err) }
    var t = setTimeout(() => { next({message: 'timeout'}) }, timeout);
    Person.create(req.body, function(err, pers) {
      if(err) { return next(err) }
      try {
        removeMany(function(err, data) {
          clearTimeout(t);
          if(err) { return next(err) }
          if(!data) {
            console.log('Missing `done()` argument');
            return next({message: 'Missing callback argument'});
          }
          Person.count(function(err, cnt) {
            if(err) { return next(err) }
            if (data.ok === undefined) {
              // for mongoose v4
               try {
                data = JSON.parse(data);
              } catch (e) {
                console.log(e);
                return next(e);
              }
            }
            res.json({
              n: data.n,
              count: cnt,
              ok: data.ok
            });
          })
        });
      } catch (e) {
        console.log(e);
        return next(e);
      }
    });
  })
});

var chain = require('./myApp.js').queryChain;
router.post('/query-tools', function(req, res, next) {
  var t = setTimeout(() => { next({message: 'timeout'}) }, timeout);
  Person.remove({}, function(err) {
    if(err) if(err) { return next(err) }
    Person.create(req.body, function(err, pers) {
      if(err) { return next(err) }
      try {
        chain(function(err, data) {
          clearTimeout(t);
          if(err) { return next(err) }
          if (!data) {
            console.log('Missing `done()` argument');
            return next({ message: 'Missing callback argument' });
          }
          res.json(data);
        });
      } catch (e) {
        console.log(e);
        return next(e);
      }
    });
  })
});

app.use('/_api', enableCORS, router);

// Error handler
app.use(function(err, req, res, next) {
  if(err) {
    res.status(err.status || 500)
      .type('txt')
      .send(err.message || 'SERVER ERROR');
  }
});

// Unmatched routes handler
app.use(function(req, res){
  if(req.method.toLowerCase() === 'options') {
    res.end();
  } else {
    res.status(404).type('txt').send('Not Found');
  }
})

var listener = app.listen(process.env.PORT || 3000 , function () {
  console.log('Your app is listening on port ' + listener.address().port);
});

/********************************************
 * DO NOT EDIT THIS FILE
 * the verification process may break
 *******************************************/

# Environment Config

# store your secrets and config variables in here
# only invited collaborators will be able to see your .env values

# reference these in your code with process.env.SECRET
SECRET=
MADE_WITH=
MONGO_URI=mongodb://<Arjun>:<arjundataneja>@ds012889.mlab.com:12889/arjundataneja

# note: .env is a shell file so there can't be spaces around =

post your glitch link

your app works with my own connection string, so again it is a problem with your mongodb atlas setup, follow the instructions I pointed to earlier

Okay,

I feel really really silly! I was trying to pass the test with the wrong glitch url. It passed perfectly fine sharing the live page.

Thank you so much @Dereje1 for the patience and response!

Cheers

I’ll modify the instruction post to include a note of submitting the live page only, I’ve seen several errors wrt the same thing from other users as well. @Arjun8, make sure you are submitting the live page and not the glitch editor for he challenge to pass.

A new issue that has come up…

When I submit the challenge it shows the test passing and has the pop up that says submit and continue to the next challenge. When I try to move on to the next challenge it doesn’t give me credit for the previous challenges.

I’ve done the first six in the Mongoose and MongoDB section and none of the radio buttons are ticked with the green check mark.

Any ideas why this would happen?

I’m not sure, I’ve noticed it happen sometimes to me too on different challenges, try clearing your browser’s cache and resubmitting it…, none of the challenges ‘credits’ go towards the certificates anyway, only the projects do.

I have solved it somehow!
Thanks a lot :pray:t2:

Nothing worked for me. I noticed an error that said something along the lines of “Not a String”. Wrapping up the secret URI in single quotes worked.

Try that

MONGO_URI='mongodb+srv://adam:***********@cluster4-7pwj1.mongodb.net/test?retryWrites=true&w=majority'
2 Likes