user1400312
user1400312

Reputation:

findOne Subdocument in Mongoose

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!

Upvotes: 29

Views: 33432

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 312129

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);
        }
    }
);

Upvotes: 41

Related Questions