如何在猫鼬中加入两个收藏

卢齐姆

我有两个定义如下的模式:

var WorksnapsTimeEntry = BaseSchema.extend({
 student: {
     type: Schema.ObjectId,
     ref: 'Student'
 },
 timeEntries: {
     type: Object
 }
 });

var StudentSchema = BaseSchema.extend({
firstName: {
    type: String,
    trim: true,
    default: ''
    // validate: [validateLocalStrategyProperty, 'Please fill in your first name']
},
lastName: {
    type: String,
    trim: true,
    default: ''
    // validate: [validateLocalStrategyProperty, 'Please fill in your last name']
},
displayName: {
    type: String,
    trim: true
},
municipality: {
    type: String
    }
});

我想遍历每个学生,并显示时间条目。到目前为止,我有这段代码显然不正确,因为我仍然不知道如何加入WorksnapTimeEntry模式表。

Student.find({ status: 'student' })
        .populate('student')
        .exec(function (err, students) {
            if (err) {
                return res.status(400).send({
                    message: errorHandler.getErrorMessage(err)
                });
            }
            _.forEach(students, function (student) {
               // show student with his time entries....
            });
            res.json(students);
        });

谁知道我该怎么做到?

布雷克七

您不需要.populate()在这里,而是想要两个查询,第一个查询与Student对象匹配以获取_id值,第二个查询将用于$in匹配WorksnapsTimeEntry那些“学生”的各个项目。

async.waterfall使用它来避免一些压痕蠕变:

async.waterfall(
    [
        function(callback) {
          Student.find({ "status": "student" },{ "_id": 1 },callback);
        },
        function(students,callback) {
            WorksnapsTimeEntry.find({
                "student": { "$in": students.map(function(el) {
                    return el._id
                })
            },callback);
        }
    ],
    function(err,results) {
       if (err) {
          // do something
       } else {
          // results are the matching entries
       }
    }
)

如果确实需要,则可以.populate("student")在第二个查询上从另一个表中获取填充项。

相反的情况是查询WorksnapsTimeEntry并返回“一切”,然后使用“匹配”查询选项过滤掉所有null结果.populate()

WorksnapsTimeEntry.find().populate({
    "path": "student",
    "match": { "status": "student" }
}).exec(function(err,entries) {
   // Now client side filter un-matched results
   entries = entries.filter(function(entry) {
       return entry.student != null;
   });
   // Anything not populated by the query condition is now removed
});

因此这不是理想的操作,因为“数据库”没有过滤可能的大部分结果。

除非您有充分的理由不这样做,否则您可能应该“应该”“嵌入”数据。这样,"status“”之类的属性已在集合中可用,并且不需要其他查询。

如果您正在使用像MongoDB这样的NoSQL解决方案,那么您应该拥抱它的概念,而不是遵循关系设计原则。如果您一直在进行关系建模,那么您最好也使用关系数据库,因为使用其他方式处理该解决方案将不会带来任何好处。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章