【问题标题】:fetch query returning empty array when using params使用参数时获取返回空数组的查询
【发布时间】:2019-10-17 17:08:49
【问题描述】:

我正在尝试使用 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"]
);

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

【问题讨论】:

  • 感谢 EddieDean 的回答。现在可以正常使用了。

标签: javascript node.js mongodb adonis.js


【解决方案1】:

这可能是由于您的身份验证中间件返回了一个 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;
  }

【讨论】:

    猜你喜欢
    • 2019-10-27
    • 2023-04-03
    • 1970-01-01
    • 2015-01-18
    • 2016-03-24
    • 2015-11-26
    • 2018-06-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多