Search code examples
node.jsmongodbsails.jssails-mongo

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."
    );
  },

Solution

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