简体   繁体   中英

Failed to filter array of data based on there condition

I want to retrieve based on their list of IDs given. 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

[
  {
    "_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.

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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