Dev M
Dev M

Reputation: 1709

how to find in an Array of Objects by id?

I want to use mongoose to find in an array of objects by id.

I have this list:

 {
   "data":[
      {
         "_id":"60ce0ea7eb945a22288fd0ba",
         "parent":"50ce0e44eb945a22288fd0b1",
         "label":"label 1-2",
         "ancestors":[
            {
               "_id":"50ce0e44eb945a22288fd0b1",
               "label":"label 1-1"
            },
            {
               "_id":"40ce077e90c6262bdc21aa44",
               "label":"label 1"
            }
         ]
      },
      {
         "_id":"50ce0e44eb945a22288fd0b1",
         "parent":"60ce077e90c6262bdc21aa55",
         "label":"label 1-1",
         "ancestors":[
            {
               "_id":"40ce077e90c6262bdc21aa44",
               "label":"label 1"
            }
         ]
      },
      {
         "_id":"40ce077e90c6262bdc21aa44",
         "parent":null,
         "label":"label 1",
         "ancestors":[]
      }
   ]
}

This is the schema:

const categorySchema = new mongoose.Schema(
  {
    label: {
      type: String,
      required: true
    },
    parent: {
      type: ObjectId,
      default: null,
      ref: 'category'
    },
    ancestors: [
      {
        _id: {
          type: ObjectId,
          ref: 'category'
        },
        label: String
      }
    ]
  },
  { timestamps: true }
);

I tried to do this:

  async getDescendants(req, res) {
    let { pId } = req.body;
    if (!pId) {
      return res.json({ error: 'All filled must be required' });
    } else {
      try {
        const data = await patternModel
          .find({ 'ancestors._id': pId })
          .select({
            _id: false,
            label: true
          })
          .exec();
   
        if (data) {
          return res.json({ data });
        }
      } catch (err) {
        return res.json({ err: err });
      }
    }
  }

this is my actual result:

{
  "data": []
}

when I change .find({ 'ancestors._id': pId }) to .find({ 'ancestors.label': label }) it works but not for the id.

Upvotes: 1

Views: 61

Answers (1)

Tushar Shahi
Tushar Shahi

Reputation: 20441

It is not a simple field. It is an array of subdocuments. Use elemMatch.

Edit: When querying _id fields you will have to wrap convert them into ObjectIds (specific to Mongo).

let newPid = mongoose.Types.ObjectId(pId);

 const data = await patternModel.find({ ancestors: { $elemMatch : { _id: newPid} }  })
.select({ _id: false,label: true })
.exec();

Upvotes: 1

Related Questions