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)