node.js 在猫鼬中查找一个子文档

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13460765/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 16:40:50  来源:igfitidea点击:

findOne Subdocument in Mongoose

node.jsmongodbexpressmongoose

提问by JohnnyHK

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

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

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!

任何帮助,将不胜感激!

回答by JohnnyHK

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

您缺少teamMembers对象的级别,因此您的代码需要更改为如下所示:

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