【问题标题】:How to make .populate exclude null values?如何使 .populate 排除空值?
【发布时间】:2017-03-02 20:57:57
【问题描述】:

有没有办法排除等于 null 的 Lessons.lesson_id?我从以前的答案中得到了以下内容,但它仍然给出了为空的课程.lesson_id

module.exports.getClasses = function(id, callback){
    Class.findById(id)
    .populate(
        {path: 'lessons.lesson_id',
        model: 'Lesson', $ne: null}
    ).exec(callback)
}

var classSchema = new Schema({
    title: { type: String, required: true },
    lessons: [{
        _id: false,
        lesson_id: {type: mongoose.Schema.Types.ObjectId, ref: 'Lesson'}
    }],
});

我正试图阻止带有 null 的课程 ID 出现

{ _id: 58090,
  title: 'vcvc',
  __v: 0,
  lessons: [ { lesson_id: null }, { lesson_id: [Object] } ] }

【问题讨论】:

  • 您是否希望没有任何课程没有空课?我不清楚您期望的查询结果是什么。
  • 对不起,我应该更清楚。如果一个教训 = null,那么我不希望它被填充。

标签: node.js mongodb express mongoose mongodb-query


【解决方案1】:

所以您的 ClassSchema 是一个触发点,我想您可能会发现这会根据您的要求更好地工作:

var classSchema = new Schema({
    title: { type: String, required: true },
    lessons: [{type: mongoose.Schema.Types.ObjectId, ref: 'Lesson'}],
});

【讨论】:

    猜你喜欢
    • 2020-03-27
    • 1970-01-01
    • 2017-02-20
    • 2011-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-13
    相关资源
    最近更新 更多