使用MongoDB`$ in`运算符转换和传递数字数组

时间:2018-11-15 18:32:13

标签: arrays mongodb

在我的MongoDB / Node后端中,我传入传入的参数,然后过滤一些数据。

我要做的第一件事是接受字符串值(恰好代表数字),例如“ 1”,“ 2”等,然后将它们转换成逗号分隔的数组。

现在,我需要过滤名为“ responsibilitySequence”的属性。问题是,此属性的值是“数字”类型,而不是“字符串”类型。

那么我该如何调整以下函数,以使Mongo可以使用$in运算符作为数组传入的内容由数字而不是字符串值组成?

  if (responsibilitySequence) {
    let arrResponsibilitySequence = [];
    arrResponsibilitySequence = responsibilitySequence.split(",");
    _.each(arrResponsibilitySequence, (l, key, c) => {
      arrResponsibilitySequence[key] = new RegExp(arrResponsibilitySequence[key], "i");
    });
    search.responsibilitySequence = {
      $in: arrResponsibilitySequence
    };
  }

1 个答案:

答案 0 :(得分:1)

您可以映射值并将其解析为int

  if (responsibilitySequence) {
    let arrResponsibilitySequence = responsibilitySequence.split(",");
    search.responsibilitySequence = {
      $in: arrResponsibilitySequence.map(x => Number.parseInt(x)) // or just +x
    };
  }