2

I'm following a tutorial to create a simple Node/Express/Mongoose REST API. I'm running mongod in one terminal and my node app in another.

My app:

// BASE CONFIG
// =========================================================
var express = require('express'),
    bodyParser = require('body-parser'),
    util = require('util'),
    app = express(),
    port = process.env.PORT || 8000,

    // database
    dbURI = 'mongodb://localhost/nodeSpace',
    mongoose = require('mongoose'),
    db = null,

    // models
    Ship = require('./models/ship');

// configure use of bodyParser this lets us get data from a post
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());


// DB SETUP
// =========================================================
mongoose.connect(dbURI);
db = mongoose.connection;

db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function () {
    console.log('Connected to DB!');
})

var testModel = mongoose.model('Test', new mongoose.Schema({name: String}, {bufferCommands: false}));

testModel.find(function (err, res) {
    if(err) {
        console.log('Error finding test model: ' + err);
    }
    else {
        console.log('Got test model: ' + res);
    }
});

When it runs, mongo is reporting connections formed:

2017-03-28T10:44:28.565-0600 I -        [conn51] end connection 127.0.0.1:49289 (5 connections now open)
2017-03-28T10:44:28.565-0600 I -        [conn50] end connection 127.0.0.1:49288 (5 connections now open)
2017-03-28T10:44:28.565-0600 I -        [conn47] end connection 127.0.0.1:49285 (5 connections now open)
2017-03-28T10:44:28.565-0600 I -        [conn49] end connection 127.0.0.1:49287 (5 connections now open)
2017-03-28T10:44:28.565-0600 I -        [conn48] end connection 127.0.0.1:49286 (5 connections now open)

But my app chokes on the 'find' call on my test model. Even if the database returned no results, I'd expect it to just be an empty object:

/node_modules/mongoose/lib/drivers/node-mongodb-native/collection.js:129
    collection[i].apply(collection, args);
                ^

TypeError: Cannot read property 'find' of null
    at NativeCollection.(anonymous function) [as find] (/node_modules/mongoose/lib/drivers/node-mongodb-native/collection.js:129:17)
    at Query.execFind (/node_modules/mongoose/lib/query.js:1682:20)
    at Query.find (/node_modules/mongoose/lib/query.js:204:15)
    at Function.find (/node_modules/mongoose/lib/model.js:821:16)
    at Object.<anonymous> (/server.js:34:11)
    at Module._compile (module.js:571:32)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:488:32)
    at tryModuleLoad (module.js:447:12)
    at Function.Module._load (module.js:439:3)
4
  • In what line is the error happening? It looks you are missing validation for when res is null (no results). Commented Mar 28, 2017 at 17:15
  • It doesn't actually tell me the line but there's only one "find" call. The issue makes it seem like "find" doesn't exist on "testModel" or testModel is null. Could this be an issue with mongoose forming a valid connection? Commented Mar 28, 2017 at 17:29
  • Did you actually confirmed that, by console logging testModel? Commented Mar 28, 2017 at 17:33
  • I logged a different model in an identical situation and it was not null. robertklep's answer below resolves the symptom but not my underlying problem. I think the real issue is the mongo connection. Commented Mar 28, 2017 at 18:07

2 Answers 2

4

The issue is setting bufferCommands to false. When you do that, you have to wait for the connection to the database to be made before you can issue any queries (either inside the open event handler, by passing a callback to mongoose.connect(), or by waiting for the promise returned by that function to be resolved).

Sign up to request clarification or add additional context in comments.

4 Comments

So maybe my real issue is the connect. This does successfully make the "find" error go away but it hangs indefinitely on the find function and never returns an error or success. I think my core issue is my mongoose connection but I'm not sure how to debug...mongo terminal reports connections formed.
The find hanging is a sign that Mongoose can't connect properly. I'm not sure how to interpret the MongoDB logs (it says "end connection ..."). You're not calling db.close() (or mongoose.disconnect()) anywhere?
Nope. The stuff I posted is the entire app except for an "app.listen" call that I missed on the paste. I might wait a bit to accept the answer in case someone has insight on the underlying problem. But this at least gives me some direction. Thanks!
It turns out that my real issue was with dependencies. I'm accepting this as the answer to the specific symptoms but posted a supplemental answer as well.
0

I'm accepting the previous answer because it is correct for the reported symptoms. However, the underlying cause was a different problem and this answer may be useful.

Various local and remote databases hung indefinitely on any type of query. Forcing unbuffered queries caused the issues reported in the original question. My mongod reported connections when the app started but no connection events fired. It appears to be a dependency versioning issue.

The tutorial here: https://scotch.io/tutorials/build-a-restful-api-using-node-and-express-4

References these dependencies:

"dependencies": {
    "express": "~4.0.0",
    "mongoose": "~3.6.13",
    "body-parser": "~1.0.1"
}

But something with that collection of packages simply doesn't work. I tried both a locally-installed mongo and a free cloud hosted install. Neither worked. After updating my dependencies to this, both local and cloud installs connected and queried without issues:

"dependencies": {
  "body-parser": "^1.17.1",
  "express": "^4.15.2",
  "mongoose": "^4.9.2"
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.