mongoose doesn't return the output with findById

mongoose update
mongoose exec
mongoose findoneandupdate
mongoose connect
mongoose schema
mongoose populate
mongoose npm
mongoose limit

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);
};

1. console your req.params before if

loc8r/app_api/controllers/locations.js

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

module.exports.locationsReadOne =  function (req, res) {

console.log(req.params)

    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);
};

if params empty, or console not work, then check your route path

or

  1. console something inside sendJsonResponse, maybe your function not work. Because if permanently show loading, it mean you dont send response.

or

  1. Try to update mongodb to latest version, maybe mongoose work not correct with mongodb 2.1.18. It`s realy very old version.

Mongoose v5.9.20: Queries, findOne({ _id: idString }); // Does **not** find the `Person`, because Mongoose doesn't cast aggregation // pipelines. const aggRes = await Person.aggregate([{  While the Mongoose Deception doesn’t have a real suspension system (again, it’s a $200 bike, what do you expect), but the front fork does have a shock absorber in it.


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');

mongoose doesn't return the output with findById, 1. console your req.params before if. loc8r/app_api/controllers/locations.js var mongoose = require('mongoose'); var Loc = mongoose.model('Location');  This will happen whenever a key's value is a POJO that doesn't have a type property. In these cases, Mongoose only creates actual schema paths for leaves in the tree. (like meta.votes and meta.favs above), and the branches do not have actual paths. A side-effect of this is that meta above cannot have its own validation.


try rewrite location controller like this

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

exports.locationsReadOne = function (req, res) {
    if (req.params && req.params.locationid)
        Location.findById(req.params.locationid, function (err, location) {
            if (err) return res.status(500).send(err);
            if (location) return res.status(200).json(location);
            return res.status(404).json({"message": "locationid not found"})
        })
    else
        return res.status(200).json({"message": "no location id in request"})
}

Node.js, MongoDB and Angular Web Development: The definitive guide , Mongoose is an Object Document Model (ODM) library that provides additional Mongoose doesn't replace the MongoDB Node.js native driver; instead,  The banded mongoose of sub-Saharan Africa is one of the most populous species and therefore not endangered, according to the International Union for Conservation of Nature. He is found in every country from Senegal and Gambia in the west to Eritrea, Ethiopia and Somalia in the east and into South Africa.


Hey try by converting your id to object id

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

exports.locationsReadOne = function (req, res) {
if (req.params && req.params.locationid)
    Location.findById(mongoose.Types.ObjectId(req.params.locationid), function (err, location) {
        if (err) return res.status(500).send(err);
        if (location) return res.status(200).json(location);
        return res.status(404).json({"message": "locationid not found"})
    })
else
    return res.status(200).json({"message": "no location id in request"})
}

Express Tutorial Part 3: Using a Database (with Mongoose), Mongoose: Mongoose is a MongoDB object modeling tool designed to the MongoDB database driver, but it does not install MongoDB itself. const schema = new mongoose.Schema updateOne() doesn't require you to load the document into memory, which may give you better performance if your documents are huge.


The Mongoose Diaries, That doesn't mean I had to like it. what Mom would think now that I eat lots of meat, in part because my inner Mongoose doesn't care for vegetarian fare. Death Knights will be the other tanking class that doesn't use shields, so will be using a slow-attack 2h weapon. So I imagine Mongoose will be popular for them as well. And of course, for a Warrior who can dual-wield two slow 2h weapons, this will be amazing. EDIT 3.0.8: Mongoose is still the best tanking chant in the game for Bear Tanks.


Mongoose doesn't return a VersionError when saving · Issue #6112 , Do you want to request a feature or report a bug? Bug What is the current behavior? Mongoose will save a document with an old version  Mongoose provides a straight-forward, schema-based solution to model your application data. It includes built-in type casting, validation, query building, business logic hooks and more, out of the box.


Mongoose doesn't shut down gracefully · Issue #1807 · Automattic , Mongoose never lets the node event loop clear, even after disconnect is called. This stops node from exiting gracefully (i.e. without calling process.exit()) Other  @Connor Yea, it is a default feature in mongoose, although there is an option to fix this. Check my updated answer. – user2441535 Nov 1 '15 at 20:39 Kind of a strange little quirk, but I s'pose the developers had their reasons.