Long story short, I have in my MongoDB database a collection of posts and with node.js, express and mongoose, I'm trying to find all the documents using the $where method.
So I try this and it works perfectly, all the results, if their name includes Jo get returned.
app.get("/posts", (req, res) => {
  const nameSearch = "Jo";
  Post.find({
    $where: function () {
      return this.name.includes("Jo");
    },
  }).then((data) => res.send(data));
});
But if I do something like this, it throws me an error
app.get("/posts", (req, res) => {
  const nameSearch = "Jo";
  Post.find({
    $where: function () {
      return this.name.includes(nameSearch);
    },
  }).then((data) => res.send(data));
});
Also, if I do this, it says that $where requires a string or a function.
function runThis(post) {
      return post.name.includes("Jo");
}
app.get("/posts", (req, res) => {
  Post.find({
    $where: runThis(this),
  }).then((data) => res.send(data));
});
Even weirder, I think, is that if I change the function inside the $where to an arrow function, no matter what I put in the function, it will return all the results
app.get("/posts", (req, res) => {
  const nameSearch = "Jo";
  Post.find({
    $where: () => {
      return this.name.includes("Jo");
    },
  }).then((data) => res.send(data));
});
 
     
    