Need advise last lesson of mongodb/mongoose

Hi, i’m studying this lesson, following your hint i’ve written this code for the query chain:

const queryChain = (done) => {
  const foodToSearch = "burrito";

Person.find({favoriteFoods: foodToSearch})
  .sort({ name: -1 })
  .limit(2)
  .select({ age: 0 })
  .exec(function(error, people) {
    
    if(error) return console.log(error);
    
    
    done(error, data)
  });

};

there sure be something wrong, i don’t pass the test, hope you can lead me to the solution!

Also in the mongoose’s documentation can’t find model.sort :thinking:

Hello, buddy. You may use .sort({name: 1}) instead .sort({name -1}). Have fun! :wink:

I’ve written this code:

Person.find({favoriteFoods: foodToSearch})
  .sort({ name: 1 })
  .limit(2)
  .select({ age: 0 })
  .exec(function(error, people) {
    
    if(error) return console.error(error);

  
    
    done(error, data)
  });

};

but still doesn’t work, it gives me error. Hope for your help

As mentioned in the documentation, the .find() method applied on a Model returns a Query. So you should look into Query.sort() :slight_smile:

const queryChain = (done) => {
const foodToSearch = "burrito";
  Person.find({favoriteFoods : foodToSearch})
           .sort({name:1})
           .limit(2)
           .select({age:0})
           .exec(function(err,data){
    if(err) return console.log(err)
    done(null, data)
  });
};

Don’t know this will help or not , can you try the done() with null and data . done(null, data)

Thank you for your advices, i’m working on it :slightly_smiling_face:

I don’t know if the tests are buggy or not but in some cases when the tests say timed out try to re run it multiple times… it works for the 2nd or the 5th time

this is the only thing seems to work… as our code is correct but it seems that the most of the mongo and mongoose section tests are all buggy

1 Like

Thanks, this worked for me

I believe the lesson suggests that you store the results in a variable for later execution through .exec(). Although the lesson teaches to use this syntax, async await with a Try & Catch block is more efficient. Below is the coding I used to solve this lesson. From my understanding it’s always good practice to return the data to the client but in this case there really isn’t one so I returned it in the console instead:

const queryChain = (done) => {
  const foodToSearch = "burrito";
  
  const findPerson = 
    Person
    .find({favoriteFoods: foodToSearch})
    .sort({name: 1})
    .limit(2)
    .select({age: 0})
    .exec((err, data) => {
      if(!err) {
      done(null, data);
      console.log(`Chained  Successfully. Results: ${data}`)
      } else {
        console.log(err);
      };
    });
};
1 Like