Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

findOne works but not get all/find

findOne works fine

db.collection('updates', function (err, collection) {
        collection.findOne({
            author: req.user._id
        }, function (err, doc) {
        }
 });

I'm trying to get all the documents instead of just one. I'm changing findOne to find (shown below) and it doesn't work. How do I fix this?

        db.updates.find({
            author: req.user._id
        }, function (err, doc) {
        }

The error message: It's saying Cannot call method "find" of undefined, meaning the collection isn't being recognized.

Update: This doesn't work either:

db.collection('updates', function (err, collection) {
        collection.find({ //changed findOne to find
            author: req.user._id
        }, function (err, doc) {
        }
 });
like image 275
UX Guy Avatar asked Mar 17 '23 10:03

UX Guy


1 Answers

It looks like you're using Native MongoDB Node.JS Driver to query your database. According to its readme, you should use .toArray() method to instantiate MongoDB cursor, returned from .find() call:

collection.find({
  author: req.user._id
}).toArray(function (err, docs) {
  // docs is an Array of documents here
});

If you have troubles with Native MongoDB Node.JS Driver, I would suggest using some wrapper around it with more intuitive API, e.g.:

  • mongojs
  • monk
  • mongoskin
like image 94
Leonid Beschastny Avatar answered Mar 28 '23 00:03

Leonid Beschastny