简体   繁体   English

无法根据条件过滤数据数组

[英]Failed to filter array of data based on there condition

I want to retrieve based on their list of IDs given.我想根据他们给出的 ID 列表进行检索。 There is a list of ids I used inside my controller I want to retrieve all the objects array based on the given list of ids to me here is a prototype of my database record how it looks like我在 controller 中使用了一个 ID 列表,我想根据给定的 ID 列表检索所有对象数组,这是我的数据库记录的原型

[
  {
    "_id": ObjectId("630a2e258bb6b10016ca68f1"),
        "deviceId": "42925f6a6eec14d8",
        "personId": ObjectId("630a2e218bb6b10016ca68eb"),
        "createdAt": 1661611557637,
        "updatedAt": 1661611557637,
    },
  {
    "_id": ObjectId("630a2e258bb6b10016ca68f1"),
        "deviceId": "42925f6a6eec14d8",
        "personId": ObjectId("630a2e218bb6b10016ca68eb"),
        "createdAt": 1661611557637,
        "updatedAt": 1661611557637,
    },
  {
    "_id": ObjectId("630a2e258bb6b10016ca68f1"),
        "deviceId": "42925f6a6eec14d8",
        "personId": ObjectId("630a2e218bb6b10016ca68eb"),
        "createdAt": 1661611557637,
        "updatedAt": 1661611557637,
    },
  {
    "_id": ObjectId("630a2e258bb6b10016ca68f1"),
        "deviceId": "42925f6a6eec14d8",
        "personId": ObjectId("630a2e218bb6b10016ca68eb"),
        "createdAt": 1661611557637,
        "updatedAt": 1661611557637,
    }
]

Here is what i am trying to do:这是我想要做的:

getData: async function (req, res) {

    // var db = Device.getDatastore().manager;

    let ObjectId = require("mongodb").ObjectID;

    let usersID = [
      "62f79104bb4b3d0016260b88",
      "62f925a3bcbc910016a360b6",
      "630a2e218bb6b10016ca68eb",
    ];

    var devices = await Device.find({
      personId: {
        $in: [...usersID],
      },
    });
    if (!devices) {
      return res.badRequest("Please specify search criteria");
      // var devices = await Device.find();
    }
    return res.successResponse(
      devices,
      200,
      null,
      true,
      "${devices.size()} roles are found."
    );
  },

You could use aggregate to change de objectId to string and get the result you want.您可以使用聚合将 de objectId 更改为字符串并获得所需的结果。

here is an example:这是一个例子:

 const devices = await Device.aggregate([
  {
    "$addFields": {
      "personId": {
        "$toString": "$personId"
      }
    }
  },
  {
    "$match": {
      "personId": {
        $in: [
          "62f79104bb4b3d0016260b88",
          "62f925a3bcbc910016a360b6",
          "630a2e218bb6b10016ca68eb"
        ]
      }
    }
  }
])

Or:或者:

 const devices = await Device.find(
  {"personId": {
        $in: [
          ObjectId("62f79104bb4b3d0016260b88"),
          ObjectId("62f925a3bcbc910016a360b6"),
          ObjectId("630a2e218bb6b10016ca68eb")
        ]
      }
    }
).toArray();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM