0

I'm currently trying to find all the documents that have a certain value of 'bar' in the key 'foo'. Using mongodb and nodejs.

When I try to run this I get: "TypeError: Cannot read property 'find' of undefined" error return.

If I try using findOne() it'll just return the first document that has the document with the value "bar" for the key "foo", however there are 3.

module.exports = function(app, db) {

app.get('/foo', (req, res)=>{

db.collection('barCollection').find({foo: {$all: ['bar']}}
,(err, item)=>{
 if (err) {
            res.send({'error':'An error has occurred'});
        } else {
            res.send(item);
        } 
    });
 });
};

Thanks

2 Answers 2

1

Paul is right, there is some issue in your code which is why it's returning null.

Here try this snippet. I'm using 2 files for demo.

model.js

const mongoose = require('mongoose');

mongoose.connect('mongo_url');
var barSchema = new mongoose.Schema({
  // your schema
});

module.exports = mongoose.model('Bar', barSchema);

main.js

var BarCollection = require('./models'); // assuming both files are in same directory.

BarCollection.find({foo: {$all: ['bar']}}
,(err, item)=>{
 if (err) {
            res.send({'error':'An error has occurred'});
        } else {
            res.send(item);
        } 
    });
 });
};

Basically what I am trying here is:

  1. separate MongoDB model code in separate files
  2. Import mongo collection in API files for CRUD operations
1
  • 1
    Good point for recommending Mongoose. It's the best way to Mongo,imo
    – Paul
    Commented Jun 4, 2017 at 17:38
0

db.collection('barCollection') is returning null for some reason. You'll need to figure out why, it's probably somewhere else in your code since you don't have the setup logic here.

I'd look at whether mongodb was connected properly (i.e. is the db instance you're passing that function actually connected to the database), is mongodb running and available on the port you configured it with, etc.

7
  • I mean findOne() works shouldn't that mean I'm properly connected? Thank you
    – rudster
    Commented Jun 4, 2017 at 16:04
  • It should, but then something else is different in that code. The error is telling you that the return value of DB.collection('barCollection') is undefined. That means you're trying to call null.find() which of course is impossible
    – Paul
    Commented Jun 4, 2017 at 16:10
  • Now I'm getting a different error "TypeError: Converting circular structure to JSON" I think that's a step forward because it's connecting but not able to display
    – rudster
    Commented Jun 4, 2017 at 16:20
  • What did you change?
    – Paul
    Commented Jun 4, 2017 at 17:36
  • just from findOne() to find() nothing else that I've noticed, trying myke_11j advice,didn't have mongoose before
    – rudster
    Commented Jun 4, 2017 at 17:48

Not the answer you're looking for? Browse other questions tagged or ask your own question.