28

我正在尝试在 Mongoose 中对子文档进行 findOne 查询,但运气不佳...

我的架构如下所示:

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

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

我需要简单地从我正在使用此查询的文档中找到用户的电子邮件

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

任何帮助,将不胜感激!

4

1 回答 1

41

您缺少teamMembers对象的级别,因此您的代码需要更改为以下内容:

Team.findOne({'teamMembers.username': 'Bioshox'}, {'teamMembers.$': 1},
    function (err, team) {
        if (team) {
            console.log(team.teamMembers[0].email);
        }
    }
);
于 2012-11-19T20:27:57.230 回答