skip to Main Content

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?

2

Answers


  1. 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

    Login or Signup to reply.
  2. If you only want the sub document, not even the _id of the parent:

    await doc.find(
      {},
      {
        _id: 0,
        'address.text': 1
      }
    ).exec();`
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search