Learnyoumongo - Exercise 4: Find Project (Need Help!)

Ok, after my initial problems getting mongodb set up in my C9 environment, I went through the first 3 exercises. The fourth sounds really easy, but somehow my addition to the code from exercise 3 does nothing, it still returns the whole entry, with _id, name and age. Maybe some of you can tell me what I did wrong? By now I checked a solution online and it doesn’t work either, it might be my mongodb version (3.6).

var mongo = require('mongodb').MongoClient;
var url = 'mongodb://localhost:27017/learnyoumongo';
var compareAge = process.argv[2];

mongo.connect(url, function(err, client) {
  if (err) console.log('There was an error starting the client.');
  else {
    var db = client.db('learnyoumongo');
    var collection = db.collection('parrots');
    collection.find(
      {
        age: {$gt: +compareAge}
      }, {
        name: 1,
        age: 1,
        _id: 0
      }
    ).toArray(function(err,docs) {
      if (err) {
        console.log('There was an error in the find function.');
        client.close();
      } else {
        console.log(docs);
        client.close();
      }
    });
  }
})

Also: Why did I need to add a ‘+’ in front of the variable in my $gt comparison? I was stuck for some time in exercise 3 because of that until I found it in an online solution. But I didn’t find anywhere why the plus has to be there.

Will be extremely appreciative of any advice :slight_smile:

The +compareAge coerces the string compareAge into a number. Would be the same as:

age: {$gt: Number(compareAge)}
1 Like

Thanks, that makes sense. Now I just need to understand my main problem - why my code doesn’t filter out the _id property.

See my question above. I have not used Mongo, but it seems you might have some kind of syntax error there.

That part needs to be inside another pair of brackets.

So would the correct code be the following?

collection.find(
  {
    { age: {$gt: +compareAge} },
    name: 1,
    age: 1,
    _id: 0
  }
)

In this case the age object is used as the search criteria, while the other part is what is to be returned from the query.

And no to your second question.

1 Like

Thanks. I should learn Mongo so I can better answer these types of questions.

@RandellDawson

collection.find({ age: { $gt: +compareAge } }, { name: 1, age: 1, _id: 0 });

I’ve edited your post for readability. When you enter a code block into the forum, precede it with a line of three backticks and follow it with a line of three backticks to make easier to read. See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.

markdown_Forums

Oh, so this finds all the records where age is greater than compareAge and sets the record’s name, age, and _id properties with the values shown (1, 1, 0)?

It doesn’t do anything to the records. It just returns those properties. In this case 1 means true (do return this) and 0 means false (do not return this).

I guess I was missing the purpose/context of returning the other object. I think I get it now, but will start reading about Mongo.

This is the same code that I have, just in a different spacing, or am I seeing something wrong? And I tried your code, but it also just returns all three properties and doesn’t filter _id out. I think there must be something wrong with my environment at this point…

Yeah, I screwed up gave you the answer you already had. Those curly braces can get out of control.

I did Learnyoumongo a while back and, when I got stuck in a similar situation, I just started over from the beginning and it worked out. You might consider doing the same. It shouldn’t take long to get back to where you were.

Did you solve? I have the same problem there.

Hi, i am having this exact issue and it is driving me mad. Since i dont get an error it feels impossible to debug, and most of the solutions online dont work any longer. This should just be a simple projection right?

var mongo = require('mongodb').MongoClient
var url = 'mongodb://localhost:27017'
var breakpoint = parseInt(process.argv[2])

mongo.connect(url, function (err, client) {
  if (err) return console.log(err)

  var db = client.db('learnyoumongo')
  var parrots = db.collection('parrots')
  parrots.find({ age: {$gt: breakpoint}},{ name: 1, age: 1, _id: 0})
  .toArray(function (err, documents) {
    if (err) return console.log(err)

    console.log(documents)
    client.close()
  })
})

It’s probably not working because you are not firing the callback for the find method and the .toArray method is consequently working with nothing, I would try something like the below (see comments for the modified parts)

var mongo = require('mongodb').MongoClient
var url = 'mongodb://localhost:27017'
var breakpoint = parseInt(process.argv[2])

mongo.connect(url, function (err, client) {
  if (err) return console.log(err)

  var db = client.db('learnyoumongo')
  var parrots = db.collection('parrots')
  parrots.find({ age: {$gt: breakpoint}},{ name: 1, age: 1, _id: 0},(err,foundParrots)=>{//add callback to fire once parrots found
    foundParrots.toArray(function (err, documents) {//use the toArray method on the foundParrots
        if (err) return console.log(err)
    
        console.log(documents)
        client.close()
      })
  })
})

Hi
The instructions dont mention anything about collection.find needing a callback and it worked fine last assignment. It returns the documents that correspond to my query, it just shows the _id field too, which i want to avoid. According to the reference i should be doing it alright i think https://docs.mongodb.com/manual/reference/method/db.collection.find/

collection.find({
      name: 'foo'
    }, {
      name: 1
    , age: 1
    , _id: 0
    }).toArray(function(err, documents) {
    
    })

is how the program instructs me to do it. I tried your solution but it returns the same as me:
actual output vs expected output
“[ { _id: 5af2b57db4df177b4f22aace, name: ‘Jenny’, age: 10 } ]” != “[ { name: ‘Jenny’, age: 10 } ]”

Anyways i appreciate the help :slight_smile:

Actually just tried your original solution and it passes for me:

My solution (from 8 months ago) also passes for me:

So , don’t know what to tell you, restart your machine, reset your db link, etc… but it is not your code that is the issue, good luck…

Edit:
FYI: One other point in case of oversight, you have to submit your solution while you are in the correct lesson. so
learnyoumongo
select FIND PROJECT
learnyoumongo verify <solution file.js>

The reason I am pointing this out is that it is easy to forget and submit a solution for a different lesson, which will fail…