Locohost
Locohost

Reputation: 1702

Mongo collection has no .find method

I have a database on MongoLab. It has several collections. All but one work. One collection is called "selectopts". It has two documents. I can clearly see these two documents.

In my express code I have...

var db = require('mongojs');
db.connect('mongodb://xxxx:[email protected]:53xxx/rednecks',['selectopts']);


exports.selects = function (req, res) {
    db.selectopts.find(function (err, s) {
        if (err) return;
        res.json(s);
    });
};

It always errors at db.selectopts.find..., TypeError: Cannot call method 'find' of undefined. This exact same stupid simple code works fine for four other collections. Why is just this one collection not coming back from MongoLab?

I'm so completely stumped.

EDIT...

Tried db.collection('selectopts').find(... and got this error...

enter image description here

EDIT again...

Here are the two docs in the selectopts collection on MongoLab. Do you see some problem with the docs?...

enter image description here

EDIT x 3...

This is the correct/working mongo connection setup code...

var mongojs = require('mongojs');
var db = mongojs.connect(
    'xxx:[email protected]:53xxx/rednecks',
);

See the main difference? (SMFH) :-/

Upvotes: 0

Views: 1358

Answers (2)

Locohost
Locohost

Reputation: 1702

Sometimes when I post at SO I don't receive the exact actual answer from any one reply, but somehow you guys always steer me toward the answer. In this case, it was programmer stupidity. My code at the top of the route js file is wrong. You can see it wrong at the top of this post. I edited and added the correct syntax, which magically got everything working.

To eliminate this type of repetition/syntax/non-DRY bungling, I moved the mongo connection lines into a separate database.js file and require it at the top of the route files. Genius huh?!? :-D

"Thank you" x 100 for all your replies! You always get me back on track :-)

Upvotes: 1

leorex
leorex

Reputation: 2068

Connect using the following style:

var MongoClient = require('mongodb').MongoClient;
var db;

MongoClient.connect(
    'mongodb://xxxx:[email protected]:53xxx/rednecks', 
    {auto_reconnect: true}, 
    function(e, database)
{
  db = database;
});


exports.selects = function (req, res) {
    db.selectopts.find(function (err, s) {
        if (err) return;
        res.json(s);
    });
};

Upvotes: 0

Related Questions