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
Sign up to request clarification or add additional context in comments.

1 Comment

Good point for recommending Mongoose. It's the best way to Mongo,imo
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 Comments

I mean findOne() works shouldn't that mean I'm properly connected? Thank you
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
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
What did you change?
just from findOne() to find() nothing else that I've noticed, trying myke_11j advice,didn't have mongoose before
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.