MongoDB and Mongoose - Chain Search Query Helpers to Narrow Search Results

Tell us what’s happening:
I’m not getting any errors in the console, but getting this error in the challenge page itself:

Chaining query helpers should succeed

The console shows the following,

Your app is listening on port 3000
OPTIONS
POST

Here’s my code:

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

Your project link(s)

solution: boilerplate-mongomongoose - Replit

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36

Challenge: MongoDB and Mongoose - Chain Search Query Helpers to Narrow Search Results

Link to the challenge:

  • are you returning this result?

also, perhaps looking into “hints” for this might be more helpful, happy learning :slight_smile:

I’m not returning the result. That variable was left there when I was trying to return the result but got errors. Since the done() is called in the exec() so how can I return the variable?

perhaps try looking into hint: 8 from “hints” link that i shared

and use it with a return in front of it, hopefully that would do,m happy learning :slight_smile:

Thanks @bappyasif for helping, unfortunately it still doesn’t work. My code looks like this now,

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

I’m still getting the same error that I mentioned in my question.

What’s the reason to return the result. Isn’t the returned result a Query Object taht needs to be chained to the functions that are called after the find method and then the call to the done() to return the result? Also the challenge prompt doesn’t mentiond anything about returning the result. The first challenges clearly say that we’ll follow the node convention of calling done(err) in the case of errors and calling done(null, data) when there’s no error. I was able to pass all the previous challenges with that but now it’s failing on this challenge .

  • why are you “hard coding” this variable value? isnt this supposed to be “modifiable”?!

lets read from instructions

find people who like the food specified by the variable named foodToSearch

maybe you need to make it as such that “other values” can be passed to it, perhaps try looking into removeById method

happy learning :slight_smile:

const foodToSearch = "burrito";

but this is not my code, it was there already and other methods such as removeManyPeople have the same variable. Changing ‘const’ to ‘let’ didn’t help the issue either.
Could you please answer my previous question so I can understand your logic of why to return from the function? I still don’t understand how that can help and why it is even possible to return from the find() call when there’s an exec() call in which we’re calling the done() function.
Okay so I updated the method to take an extra variable, here’s my new code

const queryChain = (searchKey, done) => {
	let foodToSearch = searchKey
	Person.find({ favoriteFoods: foodToSearch })
		.sort({ name: 1 })
		.limit(2)
		.select({ age: 0 })
		.exec((err, data) => {
			if (err) return done(err)
			done(null, data)
		})
}

This is still not working and getting the same error.

  • try it with “return” in front of it :slight_smile:
  • good question, done is returning its value to within “find()”, if you want this value to be passed to “caller of queryChain method” then you need to return something from it, otherwise it will get “undefined”

may be others can chime in, and correct me if im saying anything wrong here :slight_smile:

perhaps try looking into these topics:

Thanks so much for helping. I did try it with the return in front of it and it still errors out with the same error but looking up online it seems to be a bad practice to return from the function in this way when the done() is being called.
Could you please explain a bit more details about the caller of the function and why it receives undefined but none of the challenges before needed a return statement? What makes this single challenge so different that we need to now return the result to the caller?

I put a console.log() inside the tester method in the server.js file, right before the call to res.json(data) I’m console logging data and it’s containing the query result that seems to be correct. so can someone please help me figure out what is causing the challenge to not pass and throw an error? I’ll post the console result and the error as well. Thanks for helping!

server.js

const chain = require("./myApp.js").queryChain;
router.post("/query-tools", function (req, res, next) {
  let t = setTimeout(() => {
    next({ message: "timeout" });
  }, TIMEOUT);
  Person.deleteOne({}, function (err) {
    if (err) {
      return next(err);
    }
    Person.create(req.body, function (err, pers) {
      if (err) {
        return next(err);
      }
      try {
        chain(function (err, data) {
          clearTimeout(t);
          if (err) {
            return next(err);
          }
          if (!data) {
            console.log("Missing `done()` argument");
            return next({ message: "Missing callback argument" });
          }
          console.log(`data: ${data}`)
          res.json(data);
        });
      } catch (e) {
        console.log(e);
        return next(e);
      }
    });
  });
});

console result

Your app is listening on port 3000
OPTIONS
POST
data: {
  favoriteFoods: [ 'steak', 'burrito' ],
  _id: 6447119a2a4037010a9b6ab1,
  name: 'Ashley',
  __v: 0
},{
  favoriteFoods: [ 'steak', 'burrito' ],
  _id: 6447116523489300eadf2303,
  name: 'Ashley',
  __v: 0
}

myApp.js

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

challenge error

Failed:Chaining query helpers should succeed

as suggested by @bappyasif , I tried returning the result of the chain calls in the queryChain function as well as tried to pass a second argument to the queryChain function and change foodToSearch to be set to this passed argument. none of these worked though. I also tried to use a function inside the exec() instead of the arrow function but this didn’t work either.

You are returning the same person twice, it should be two different people.

Not sure why, but you have Person.deleteOne in server.js but it should be Person.remove (line: 372 in server.js)

Did you change it?


Just to be clear, when I change it back to use the correct method in server.js your code passes the test for me (with my own DB).

Not sure why you have that method but you should definitely not be changing the code in the server file.

1 Like

Thanks so much for helping me figure this out. I started from scratch and that reverted those methods in the server.js for me and now my solution in myApp.js works. The reason I changed those method was because I found someone in one of the page suggesting that change.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.