一尘不染

猫鼬中的findOne子文档

node.js

我在子文档的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);
    }
});

任何帮助,将不胜感激!


阅读 203

收藏
2020-07-07

共1个答案

一尘不染

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

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