2017-11-06 5 views
1

今日私は問題の前にいます。私は、私のアプリケーションのバックエンドを処理するために、mongooseで明示的なmongodbを使用しています。1つのレフを持つすべての子供を見つける1つのクエリ

親にObjectIdリファレンスを持つモデルが1つあります。この親を含むすべてのドキュメントを取得したいと思います。しかし、私はIDの親ではない名前だけを受け取っています。

私が見つけた唯一の解決策は、IDを見つけるために最初のクエリを実行してから、もう1つは自分のドキュメントを見つけることだとわかりました。 1つのクエリでそれが可能かどうかを知りたいですか?

マイモデル:

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

ありがとうございます。しかし、それは私のスキーマでそれを行う方法ですか?私は私の子供を作成するときに2つのクエリを避けるために私の子供の中の親を取得したいので。 –

関連する問題