var http = require("http");
var url = require("url");
var path = require("path");
var mongo = require("mongodb");
var Server = mongo.Server,
Db = mongo.Db,
BSON = mongo.BSONPure;
var server = new Server('localhost', 27017, {
auto_reconnect: true
});
db = new Db('gamedb', server);
db.open(function(err, db) {
if (!err) {
console.log("Connected to gameapp database");
db.collection('games', {
strict: true
}, function(err, collection) {
if (err) {
console.log("cant connect to db");
}
});
}
});
var findAll = function(req, res) {
db.collection('games', function(err, collection) {
collection.find().limit(10).toArray(function(err, items) {
res.send(items);
});
});
};
http.createServer(function(req, res) {
if (req.url == "/games" & req.method == "GET") {
res.writeHead(200, {
'Content-Type': 'text/plain'
});
findAll(req, res);
res.end('end request\n');
} else {
res.writeHead(200, {
'Content-Type': 'text/plain'
});
res.end('HI\n');
}
}).listen(3000, '127.0.0.1');
console.log('Server running at http://127.0.0.1:3000/');
I keep trying to call findAll()
in my create server function but I always get an error message saying undefined is not a function
. I double checked my syntax and I can't find any errors. Any insight?
EDIT:
EXACT ERROR MESSAGE:
Connected to gameapp database
Server running at http://127.0.0.1:3000/
/Users/Justin/Documents/git/CISC474/gameapp/node_modules/mongodb/lib/mongodb/connection/base.js:246
throw message;
^
TypeError: undefined is not a function
at /Users/Justin/Documents/git/CISC474/gameapp/server1.js:29:18
at /Users/Justin/Documents/git/CISC474/gameapp/node_modules/mongodb/lib/mongodb/cursor.js:197:9
at /Users/Justin/Documents/git/CISC474/gameapp/node_modules/mongodb/lib/mongodb/cursor.js:228:31
at /Users/Justin/Documents/git/CISC474/gameapp/node_modules/mongodb/lib/mongodb/cursor.js:806:30
at Cursor.close (/Users/Justin/Documents/git/CISC474/gameapp/node_modules/mongodb/lib/mongodb/cursor.js:1009:5)
at getMore (/Users/Justin/Documents/git/CISC474/gameapp/node_modules/mongodb/lib/mongodb/cursor.js:806:12)
at getAllByGetMore (/Users/Justin/Documents/git/CISC474/gameapp/node_modules/mongodb/lib/mongodb/cursor.js:226:3)
at /Users/Justin/Documents/git/CISC474/gameapp/node_modules/mongodb/lib/mongodb/cursor.js:184:7
at commandHandler (/Users/Justin/Documents/git/CISC474/gameapp/node_modules/mongodb/lib/mongodb/cursor.js:734:16)
at /Users/Justin/Documents/git/CISC474/gameapp/node_modules/mongodb/lib/mongodb/db.js:1903:9
EDIT:
SOLUTION:
var findAll = function(req, res) {
db.collection('games', function(err, collection) {
collection.find().limit(10).toArray(function(err, items) {
var result = JSON.stringify(items);
res.write(result);
res.end('end request\n');