2017-11-06 1 views
1

오늘 나는 문제가 있습니다. 내 응용 프로그램의 백 엔드를 처리하기 위해 mongoose와 함께 express, mongodb를 사용하고 있습니다.하나의 심판으로 모든 어린이를 찾는 하나의 질문

부모에게 ObjectId 참조가있는 모델이 하나 있습니다. 이 부모를 포함하는 모든 문서를 검색하고 싶습니다. 하지만 이드가 아닌 부모의 이름 만 받고 있습니다.

내가 찾은 유일한 해결책은 이드를 찾기 위해 첫 번째 쿼리를 수행 한 다음 내 문서를 찾는 것입니다. 하나의 쿼리에서 그렇게 할 수 있는지 알고 싶습니다.

내 모델 :

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); 
     } 
    ); 
}); 

고마워!

+0

이름은 다음 대신 이름을 사용할 수있는 아이의 내부 ID를 사용하여 고유 경우를, 그렇지 않으면 당신은 것입니다 귀하가 지금하는 것처럼 ID로 이름을 쿼리해야합니다. – FilipRistic

답변

0

"자식"을 채우고 나중에 부모 이름으로 필터링 할 수 있습니다.

0

스키마 변경하여, 할 수있는 : 이제

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. 
}) 
+0

의견을 보내 주셔서 감사합니다. 하지만 내 스키마로 그것을 수행하는 방법은 무엇입니까? 내 아이를 만들려고 할 때 두 개의 쿼리를 피하기 위해 내 아이의 부모를 얻고 싶기 때문입니다. –

관련 문제