7

Let's say I have this schema

{
jedi: [{
       name:String
       lightsaber_color:String
      ]}
}

I want to return all and only the names of them. I tried

Jedi.find({})
    .select('jedi.name')
    .exec(function (err, jedi) {
      if (err) {
        console.log("nothing found")
      }
}

It returns me nothing, while this code returns me everything.

Jedi.find({})
        .select('jedi')
        .exec(function (err, jedi) {
          if (err) {
            console.log("nothing found")
          }
    }

I see that jedi is an array so I think that .select('jedi.name') may not work for this reason.
What is the right syntax to do so?

1 Answer 1

1

You can try with this

Jedi.find({}, {'jedi.name':1}, function (err, jedi) {
      if (err) {
        console.log("nothing found")
      }
      else{
        console.log(jedi);
      }
}
Sign up to request clarification or add additional context in comments.

6 Comments

Could you explain this syntax {'jedi.name':1}
In find query first object for query, second object you can pass whatever fields you want to get in result, hope it will work for you.
I cannot have it working. Basically it returns me the whole structure, not just the names. What's the meaning of the 1 in that code?
1 mean i have to return that field
Is is possible the problem is that the field is being populated with .populate('jedi')? Obv the example above is just trivial.
|

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.