4

I'm trying to fetch some values from a mongodb collection using lucid-mongo, and it's returning me an empty array. The functions are essentially copied from others I have somewhere else in my code, just changing where some values are.

The params.id returns the same as auth.user._id, but somehow it doesn't work. I've also tried to input the id as a raw string and it also didn't work.

//these two functions work normally
async getMonths({ auth }) {
    const day = await Day.query()
      .where({
        userId: auth.user._id
      })
      .first();

    return day;
  }
  async showMonth({ request, auth }) {
    let { date } = request.only(["date"]);

    const day = await Day.query()
      .where({
        userId: auth.user._id,
        date: date
      })
      .fetch();
    return day;
  }
//these two return me an empty array (notice they're basically the same)
  async showMonthGestor({ request, auth, params }) {
    let { date } = request.only(["date"]);

    const day = await Day.where({
      userId: params.id,
      date: date
    }).fetch();
    console.log(params.id);
    return day;
  }
  async showGestor({ auth, params }) {
    const day = await Day.query()

      .where({ userId: params.id })
      .fetch();
    console.log(day);
    return day;
  }

As per request here are the routes for the functions:

//these ones work fine
Route.post("/history", "DayController.show").middleware(["auth"]);

Route.post("/history/permonth", "DayController.showMonth").middleware(["auth"]);
//these do not (middleware "gestor" only checks if the value of "userType" 
//in auth.user is "gestor" and returns a 401 if not)
Route.post("/history/:id", "DayController.showGestor").middleware([
  "auth",
  "gestor"
]);

Route.post("/history/permonth/:id", "DayController.showMonthGestor").middleware(
  ["auth", "gestor"]
);

The output expected is a list of instances with the given query.

Filipe
  • 43
  • 4

1 Answers1

2

This is possibly due to your auth middleware returning a MongoDB-flavored ObjectId, whereas it's represented as a string in your request params. If that's the case, you'll need to cast it as an ObjectId and pass that to your query. Try this:

const { ObjectId } = require('mongodb');

async showMonthGestor({ request, auth, params }) {
    let { date } = request.only(["date"]);

    const day = await Day.where({
      userId: ObjectId(params.id),
      date: date
    }).fetch();
    console.log(params.id);
    return day;
  }
EddieDean
  • 1,492
  • 9
  • 10