Javascript 为所有子文档选择一个查询
这是我的方案,我想进行一次Javascript 为所有子文档选择一个查询,javascript,node.js,mongodb,mongoose,database,Javascript,Node.js,Mongodb,Mongoose,Database,这是我的方案,我想进行一次查询,获取所有文档和所有对象的文档 var CureSchema = mongoose.Schema({ id: Number, therapist: {type:mongoose.Schema.Types.ObjectId, ref:'User'}, supervisor: {type:mongoose.Schema.Types.ObjectId, ref:'User'},
查询
,获取所有文档
和所有对象的文档
var CureSchema = mongoose.Schema({
id: Number,
therapist: {type:mongoose.Schema.Types.ObjectId, ref:'User'},
supervisor: {type:mongoose.Schema.Types.ObjectId, ref:'User'},
parents: {type:mongoose.Schema.Types.ObjectId, ref:'User'},
children: {type:mongoose.Schema.Types.ObjectId, ref:'Child'},
startate : Date,
endDate : Date,
deleted: Boolean,
});
var Cure = mongoose.model('Cure', CureSchema);
如果使用普通查询,则输出中有objectId
{
}
从技术上讲,在mongodb中使用一个查询是不可能的,因为文档属于三个不同的集合。Mongoose可能需要做五个查询(虽然我认为三个就足够了,但我不确定Mongoose有多聪明) 但是,如果您真正想问的是如何仅使用一条mongoose指令获取子文档,那么您应该查看
还可以将聚合与$lookup一起使用
Cure.aggregate([
{
"$lookup": {
"from": "users",
"localField": "therapist",
"foreignField": "_id",
"as": "therapist"
}
},
{
"$lookup": {
"from": "users",
"localField": "supervisor",
"foreignField": "_id",
"as": "supervisor"
}
}, ...
])
你在找吗?它有用!!!!但仅限于儿童,为什么在你看来??对于另一个,它是空的ok ok。。。。如果数据库中的objectId没有数据或objectId不正确,则为Null
Cure.find()
.populate('therapist')
.populate('supervisor')
.populate('parents')
.populate('children')
.exec(resultHandler);
Cure.aggregate([
{
"$lookup": {
"from": "users",
"localField": "therapist",
"foreignField": "_id",
"as": "therapist"
}
},
{
"$lookup": {
"from": "users",
"localField": "supervisor",
"foreignField": "_id",
"as": "supervisor"
}
}, ...
])