Mike Cuddy Mike Cuddy - 1 year ago 44
Node.js Question

Issue with MongoDB, Node and Express-looking up ID in Mongo

I am currently working on a simple MEAN project and I am working on pulling one item out of my mongo db and show it on the web page. Whenever I go to the site
http://localhost:3000/api/events/5782b1dbb530152d0940a227 to see the information on the object, I get null displayed. I am, like I said, suppose to see information on this object. Here is what my code looks like:


var mongoose = require('mongoose');
var Eve = mongoose.model('Info');

var sendJSONresponse = function(res, status, content) {

module.exports.eventsReadOne = function(req, res) {
.exec(function(err, info){
sendJSONresponse(res, 200, info)
//sendJSONresponse(res, 200, {"status" : "success"});


var mongoose = require( 'mongoose' )

var eventSchema = new mongoose.Schema({
activity: String,
address: String,

mongoose.model('Info', eventSchema);


var express = require('express');
var router = express.Router();
var ctrlEvents = require('../controllers/events');

router.get('/events/:eventid', ctrlEvents.eventsReadOne);

module.exports = router;

Now, one thing that may be noticed is that I call my mongo collection events. However, I forgot that event is a key word in JS so I tried "changing" it to Info which you will see on the last line of my model. Like I said, if I go to the site http://localhost:3000/api/events/5782b1dbb530152d0940a227, where the last number is the obj _id then I should see all of the data on it. Instead, all that I see is null. Any help would be great, thank you!

my other model file, db.js, has the connection:

var mongoose = require('mongoose');
var dbURI = 'mongodb://localhost/mission';


Answer Source

Mongoose will use the model name to determine which MongoDB collection it should use. The default scheme is to take the model name, lowercase it and pluralize is, and use the result as the collection name, which in your case (using Info as model name) would be infos:

// This is where the model is created from the schema, and at this point
// the collection name is decided.
mongoose.model('Info', eventSchema);

If you want it to use a different collection, you have to explicitly tell Mongoose what collection to use by setting the collection option for your schema:

var eventSchema = new mongoose.Schema({
  activity : String,
  address  : String,
}, { collection : 'events' });

To fix the error you're stating in the comments (Schema hasn't been registered for model "mission"), you need to make sure that you change all occurrences of mongoose.model():

// To create the model:
mongoose.model('Mission', eventSchema);

// Later on, to access the created model from another part of your code:
var Eve = mongoose.model('Mission');

(although it seems to be that "mission" is the name of your database; because your collection is called events I would think that a model name Event seems much more appropriate)