29

I am attempting a findOne query in Mongoose on a subdocument but I'm not having much luck...

My Schema looks like this:

var Team = mongoose.Schema({
    teamName:       String,
    teamURL:        String,
    teamMembers:    [{username: String, password: String, email: String, dateCreated: Date}],
});

var Team = db.model('Team', Team);

I need to simply find the users email from the document in which I am using this query

Team.findOne({'teamMembers.username': 'Bioshox'}, {'teamMembers.$': 1}, function (err, team) {
    if (team) {
        console.log(team[1].email);
    }
});

Any help would be appreciated!

  • I have a pretty similar problem [Here](https://stackoverflow.com/questions/44679355/how-to-get-sub-document-only-in-mongoose) can u give a look? – Saad Jun 21 '17 at 16:02

1 Answers1

41

You're missing the teamMembers level of your object, so your code needs to change to something like this:

Team.findOne({'teamMembers.username': 'Bioshox'}, {'teamMembers.$': 1},
    function (err, team) {
        if (team) {
            console.log(team.teamMembers[0].email);
        }
    }
);
JohnnyHK
  • 305,182
  • 66
  • 621
  • 471
  • can you use .populate('teamMembers') too? – chovy Nov 19 '12 at 23:21
  • 5
    Can you explain `{'teamMembers.$': 1}` or point to documentation about it? – chovy Nov 20 '12 at 03:15
  • 4
    The `$` is the positional operator that identifies the element of the `teamMembers` array to update based on the first element that matches the query selector. Docs [here](http://docs.mongodb.org/manual/reference/operator/positional/). – JohnnyHK Nov 20 '12 at 03:18
  • I don't think the $ positional operator works for mongoose... been looking around for how to go about that... – Lion789 Jul 24 '13 at 21:46
  • In my case, It returns only one element of teamMembers. Is there any method getting all matched element? – Lion.k Dec 23 '13 at 11:57
  • @yountae.kang I know you asked a while a go but is returning one because is using `Team.findOne(...);` to return all matching change it to `Team.find(...);` – Gary Torres Jan 24 '14 at 01:24
  • 1
    @JohnnyHK's docs in comment redirect to the [update operation](https://docs.mongodb.org/manual/reference/operator/update/positional/) now. But, his usage of answer is the [projection operator](https://docs.mongodb.org/manual/reference/operator/projection/positional/). – Jinyoung Kim Feb 29 '16 at 03:55