The mongoose does not return the output with findById

advertisements

I m learning nodejs and mongodb altogether with getting MEAN application

my system specifications are

ubuntu 16.04 (64 bit)
node v 6.1.0
npm v 3.8.6

"mongodb": "^2.1.18",
"mongoose": "^4.4.16",

So far I have created schema and add an entry in mongodb collection through terminal using db.locations.save() and get the generated document _id with db.locations.find().

db.locations.find().pretty() in terminal returns below output

{
    "_id" : ObjectId("57428745e89f5c55e1d057dc"),
     // and many other path
}

Now when I open /api/locations/57428745e89f5c55e1d057dc in browser, it neither gives result nor end the request. permanently show loading.. when testing with postman.

even tried with wrong Id than it returns proper error

{"message":"Cast to ObjectId failed for value \"57428745e89f5c55e1d057dca\" at path \"_id\"","name":"CastError","kind":"ObjectId","value":"57428745e89f5c55e1d057dca","path":"_id"}

and with correct id

console.log(mongoose.Types.ObjectId.isValid(req.params.locationid));  // return true

even tried

findOne({"_id": mongoose.Types.ObjectId(req.params.locationid) })

But no results

What could be the issue? Is there any bug in mongoose or anything missing .Below are my basic files with required code

loc8r/app.js

require('./app_api/models/db');
var routesApi = require('./app_api/routes/index');
app.use('/api', routesApi);

loc8r/app_api/models/db.js

var mongoose  = require( 'mongoose' );
var mongoURI = 'mongodb://localhost/loc8r';
var mongoDB = mongoose.createConnection(mongoURI);

mongoDB.on('connected', function (){
    console.log('mongoose connected to ' + mongoURI);
});

require('./locations');


loc8r/app_api/models/locations.js

var mongoose  = require( 'mongoose' );
var openingTimeSchema = new mongoose.Schema({
days: {type: String, required: true},
opening: String,
closing: String,
closed: {type: Boolean, required: true}
});

var reviewSchema = new mongoose.Schema({
author: String,
rating: {type: Number, required: true, min: 0, max: 5},
reviewText: String,
createdOn: {type: Date, "default": Date.now}
});

var locationSchema = new mongoose.Schema({
    name: {type: String, required: true},
    address: String,
    rating: {type: Number, "default": 0, min: 0, max: 5},
    facilities: [String],
    coords: {type: [Number], index: '2dspehere'},
    openingTime: [openingTimeSchema],
    reviews: [reviewSchema]
});

mongoose.model('Location', locationSchema);

loc8r/app_api/router/index.js

var express = require('express');
var router = express.Router();
var ctrlLocations = require('../controllers/locations');

/* Locations pages */
router.get('/locations/:locationid', ctrlLocations.locationsReadOne);


loc8r/app_api/controllers/locations.js

var mongoose = require('mongoose');
var Loc = mongoose.model('Location');

module.exports.locationsReadOne =  function (req, res) {
    if(req.params && req.params.locationid) {
        Loc
        .findById(req.params.locationid)
        .exec(function(err, location) {
            if(err) {
                sendJsonResponse(res, 404, err);
                return;
            }
            if (!location) {
                sendJsonResponse(res, 404, {"message": "locationid not found"});
                return;
            }
            sendJsonResponse(res, 200, location);
        });
    } else {
         sendJsonResponse(res, 200, {"message": "no location id in request"});
    }
}

var sendJsonResponse = function(res, status, content) {
    res.status(status);
    res.json(content);
};


get the solution from mongoose documentation

Important! If you opened a separate connection using mongoose.createConnection() but attempt to access the model through mongoose.model('ModelName') it will not work as expected since it is not hooked up to an active db connection. In this case access your model through the connection you created:

so changing the way I create the connection

//var mongoDB = mongoose.createConnection(mongoURI);
mongoose.connect(mongoURI);

also need to comment all other functions/expression which use mongoDB variable


Alternative approach : ( if you do not want to change mongoDB in db.js )

in controllers/locations.js

change var Loc = mongoose.model('Location'); with below line

var conn = mongoose.createConnection('mongodb://localhost/loc8r');
var Loc = mongoose.model('Location');