【问题标题】:Find all documents where ref ID is in array查找 ref ID 在数组中的所有文档
【发布时间】:2017-10-09 15:16:41
【问题描述】:

所以我有 CourseSchema,在里面,我有:

teachers: [{
    id: {
        type: mongoose.Schema.Types.ObjectId,
        ref: "Teacher"
    },
    username: String
}]

现在我想查找一位教师的所有课程。我想象做这样的事情:

Course.find().where("teachers.id").equals(user._id).exec(function(err, courses) {};

但这总是返回空数组[]。现在,我的猜测是因为 teachers 字段是一个数组,而不仅仅是一个字符串。那么数组的 .where() 有替代方法吗?

另外,我需要 .populate() 所有课程然后搜索吗?

【问题讨论】:

    标签: arrays node.js mongodb mongoose


    【解决方案1】:

    尝试在find() 中而不是where().equals() 中使用您的查询。您真的不需要填充所有课程来查找老师的课程。

    Course.find({"teachers.id" : user._id}, function (err, courses) {
       if (err) console.log(err);
       // Your functions
    });
    

    【讨论】:

    • 我让它与“teachers._id”一起工作(即使我在模式“id”中定义)。甚至我的查询也适用于“teachers._id”
    猜你喜欢
    • 2012-01-08
    • 1970-01-01
    • 2021-11-04
    • 2016-03-21
    • 2021-01-13
    • 1970-01-01
    • 1970-01-01
    • 2020-05-17
    相关资源
    最近更新 更多