使用参数时获取查询返回空数组

时间:2019-10-17 17:08:49

标签: javascript node.js mongodb adonis.js

我正在尝试使用lucid-mongo从mongodb集合中获取一些值,并且返回了一个空数组。这些函数本质上是从代码中其他地方复制的其他函数复制而来,只是更改了某些值的位置。

params.id返回与auth.user._id相同的内容,但是以某种方式不起作用。我还尝试将id输入为原始字符串,而且也没有用。

//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;
  }

根据请求,以下是功能的路由:

//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"]
);

期望的输出是具有给定查询的实例列表。

1 个答案:

答案 0 :(得分:2)

这可能是由于您的身份验证中间件返回了MongoDB风格的ObjectId,而在请求参数中将其表示为字符串。如果是这种情况,则需要将其强制转换为ObjectId并将其传递给查询。试试这个:

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;
  }