Home > Net >  Possible to only query a sub document in Mongoose?
Possible to only query a sub document in Mongoose?

Time:11-22

This is my test collection

[
  {
    "_id": "637cbf94b4741277c3b53c6c",
    "text": "outter",
    "username": "test1",
    "address": [
      {
        "text": "inner",
        "username": "test2",
        "_id": "637cbf94b4741277c3b53c6e"
      }
    ],
    "__v": 0
  }
]

If I do

t1 = await doc.find({}, 'text').exec();
console.log(JSON.stringify(t1, null, 2));

I get

[
  {
    "_id": "637cbf94b4741277c3b53c6c",
    "text": "outter"
  }
]

So here it finds the parent text.

Question

How do I get Mongoose to query the sub document instead of the parent?

CodePudding user response:

You can project the sub document(s) like this:

t1 = await doc.find({}, {'address.text':1}).exec();

See how it works on the playground example

CodePudding user response:

If you only want the sub document, not even the _id of the parent:

await doc.find(
  {},
  {
    _id: 0,
    'address.text': 1
  }
).exec();`
  • Related