【问题标题】:Using elemMatch for a nested condition query in Mongoose在 Mongoose 中使用 elemMatch 进行嵌套条件查询
【发布时间】:2014-10-17 11:00:21
【问题描述】:

我有两个模式学生,用户 - 其中用户可以是班主任或其他指定的人。

学生架构

var StudentSchema = new Schema({
name : String,
.
.
.
owner: {
        type: Schema.ObjectId,
        ref: 'User'
    }
})

现在我想将学生分组为特定所有者。(classTeacher)

我为此编写了一个服务器 api 路由方法。

get ==> localhost:3000/api/---/user/:userId/students

userId 是classTeacherid. = req.queryUserStudentsId

exports.getUserStudents=function(req,res){

     Student
            .find()
            .select({            
                'owner': {
                    $elemMatch: {
                        _id: req.queryUserStudentsId
                    }
                }
            })
            .populate('owner')
    .exec(function(err, students) {

    };

这会导致所有学生。不仅是属于给定所有者 id 的那些。

请让我知道我错在哪里。

谢谢。

【问题讨论】:

  • find() 表示查找所有文档。

标签: node.js mongodb mongoose


【解决方案1】:

select 用于选择要包含在返回文档中的字段。您需要为find 本身提供owner 过滤器,以将学生文档过滤到仅属于req.queryUserStudentsId 的文档:

 Student.find({owner: req.queryUserStudentsId})
        .populate('owner')
        .exec(function(err, students) {
            ...
        });

如果您不需要所有者的完整详细信息,可以省略 .populate('owner') 调用。

【讨论】:

    猜你喜欢
    • 2018-08-18
    • 1970-01-01
    • 1970-01-01
    • 2019-04-01
    • 2014-08-05
    • 1970-01-01
    • 1970-01-01
    • 2012-10-17
    • 1970-01-01
    相关资源
    最近更新 更多