我有两个定义如下的模式:
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] 删除。
我来说两句