1

I have a JSON structure like this:

// Users Collection

[{
  "id": "1",
  "email": "[email protected]",
  "contacts": [
    {
      "user": "2", // reference
      "nickname": "blub"
    },
    {
      "user": "3", // reference
      "nickname": "blub"
    },
  ],
  "otherfield": "anything"
}]

The User object contains an array contacts which basically represents a list of referenced Users. To allow storing additional data (like the nickname) per user I have an array of objects and not an array of ObjectIds.

Now I would like to get the contacts populated with specifying the fields to resolve (id and email for example). So the expected output is something like this:

{
  "id": "1",
  "email": "[email protected]",
  "contacts": [
    {
      "user": {
        "id": "2",
        "email": "[email protected]",
        // without other fields 
      },
      "nickname": "blub"
    }
  ],
  "otherfield": "anything"
}

I have tried something like this

User.findById(id)
  .populate('contacts.user')
  .select('contacts.user.email')

But then my contacts array contains only empty objects.

Also if I try this:

User.findById(id).populate({
    path: 'contacts.user',
    select: 'email'
})

The outcome is just the parent user without any population:

{
  email: "[email protected]",
  id: "1"
}

2 Answers 2

3

Try

User.findById(id).populate({
    path: 'contacts.user',
    select: 'email'
})

See Populating multiple paths of the documentation.

Sign up to request clarification or add additional context in comments.

Comments

0

Finally I found what I have overlooked in the documentation (thank you @Mikey)

Story.
  findOne({ title: /casino royale/i }).
  populate('author', 'name'). // only return the Persons name
  exec(function (err, story) {
    if (err) return handleError(err);

    console.log('The author is %s', story.author.name);
    // prints "The author is Ian Fleming"

    console.log('The authors age is %s', story.author.age);
    // prints "The authors age is null'
  })

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.