一个查询,find每个孩子与一个裁判

今天我面临一个问题。 我使用快速,mongodb与mongoose来处理我的应用程序的后端。

我有一个ObjectId引用给他的父母的模型。 我想检索包含此父项的每个文档。 但我只收到父母的名字,而不是ID。

唯一的解决scheme,我发现是做第一个查询来findid,然后再找一个文件。 我想知道是否有可能在一个查询中做到这一点?

我的模特:

const childSchema = new Schema({ name: { type: String, required: true }, _exampleParent: { type: Schema.Types.ObjectId, ref: 'parents', } }); 

我的查询:

 Parent.findOne({name:req.query.parent}, function(err, values){ if(err) return next(err); Child.find({_exampleParent:values.id}, 'name', function(err, values){ if(err) return next(err); res.send(values); } ); }); 

多谢你们 !

你可以填充“小孩”,然后过滤父母的名字。

您可以通过更改模式来做到这一点:

 Pass Reference Of Child To Parent Instead of parent reference to the child. Below I am just showing an example of how to do this, do consider your variable names as mine can differ: var parentSchema = new Schema({name:{ type:'string' }, children:[{type:Schema.Types.ObjectId, ref:"child"}] }); var childSchema = new Schema({name:{type:'string'}});? var child = mongoose.model('child',childSchema); var parent = mongoose.model('parent',parentSchema); 

现在检索:

 parent.findOne({name:req.query.name}).populate('child').then((result)=>{ console.log(result.children) //will be an array of all the children having the same parent. })