如何通过引用对象获取所有的值?

我有以下模式。

var orgSchema = new Schema({ name : String, email : String, webiste : String }); var empSchema = new Schema({ name : String, email : String, role : String, org : { type: Schema.Types.ObjectId, ref: 'org'} }); var leaveSchema = new Schema({ emp : { type: Schema.Types.ObjectId, ref: 'emp'}, from : Date, to : Date, reason : String }); 

具有orgSchema对象的orgSchema和具有引用empSchema对象的empSchema

我尝试了自己

如果让一个特定组织中的所有员工,我传递org对象id在query param

 EmployeeModel.find(org: req.query.org, null , {limit: 10 , skip: 0 }, function(err, employees)( ..... ..... )); 

这工作正常。

而现在,我正试图让一个特定组织的所有员工离开。 以同样的方式,我在query param传递org ObjectId。

 LeaveModel.find(org: req.query.org, null , {limit: 10 , skip: 0 }, function(err, employees)( ..... ..... )); 

但我困扰如何得到这个? 原因仅由Employee Object引用。

谁能帮忙?

在你现在的模式中,你不能在一次调用中完成。 你可以这样做:

 var ob={}; if(req.query.to) ob.to=req.query.to; if(req.query.from) ob.from=req.query.from; if(!req.query.emp){ EmployeeModel.find(org: req.query.org, null , function(err, employees)({ var empid_arr=employees.map(function(x){return x._id}); //empid_arr has all _ids of emplyees in the org. //now getting all the leaves //building a dynamic query ob.emp={$in:empid_arr}; LeaveModel.find(ob, null , {limit: 10 , skip: 0 }, function(err, leaves){ }) }) }else{ ob.emp=req.query.emp; LeaveModel.find(ob, null , {limit: 10 , skip: 0 }, function(err, leaves){ }) } 

您不能在一次调用中实现这一点,因为leaveorg在模式中没有关系。 你必须经过employees