2016-09-06 6 views
0

私はmongooseクエリをグループ化し、$ lookupを使用してmongooseにいくつかのサブドキュメントを作成しようとしていますが、結果ドキュメントの配列は空に戻ります。 誰でも私にその理由を教えてもらえますか?集計と参照が機能しない

`` `

var mongoose = require('mongoose'), 
    Schema = mongoose.Schema; 

var answerSchema = new Schema({ 
    _user    : { type: Schema.Types.ObjectId, ref: 'User', required: true }, 
    _poll    : { type: Schema.Types.ObjectId, ref: 'Poll', required: true }, 
    _question   : [{ type: Schema.Types.ObjectId, ref: 'Question' }], 
    answer    : { type : String }, 
    }, 
    { timestamps: { createdAt: 'created_at', updatedAt: 'updated_at' } 
}); 

mongoose.model('Answer', answerSchema); 

` ``

ここに私のコードです: `` `

module.exports = { 

    index: function(req, res, next){ 

    Poll.findOne({_id: req.params.poll_id}, function(err, poll){ 
    if(err) return next(err); 

    console.log(poll); 

    Answer.aggregate([ 
     {$unwind: "$_question"}, 
     {$match: {_poll: poll._id}}, 
     {$group: { 
      _id: '$_question', 
     }}, 
     { 
      $lookup : { 
      from : 'polls', 
      localField : '_poll', 
      foreignField: '_id', 
      as: 'poll' 
      }, 
     }, 
     { 
      $lookup : { 
      from : 'questions', 
      localField : '_question', 
      foreignField: '_id', 
      as: 'questions' 
      }, 
     }, 
     { 
      $lookup : { 
      from : 'users', 
      localField : '_user', 
      foreignField: '_id', 
      as: 'user' 
      }, 
     }, 
    ], function (err, result) { 
     res.status(200).json(result); 
    }); 

    }); 
    }, 

The new subdocuments are returned empty for some reason. Please note that each answer contains the reference to ONE poll, ONE user and MANY questions.

[ 
{ 
_id: "57ce8927ea5a4f090774215d", 
poll: [ ], 
questions: [ ], 
user: [ ] 
} 
] 

` `` 誰も私の間違いを見つけられますか?

代わりに$ projectを使用する必要がありますか? $ルックアップは新しい、より良い方法だと聞きました。私はmongo 3.2.0とmongoose 4.5.8を使用しています。

ありがとうございます!

+0

Github-Flavored Markdown(トリプルバッククック付きのコードセクション)はここでは機能しません。代わりに4つのスペースでコードセクションをインデントします(これにはエディタボタンもあります) – Tomalak

答えて

0

Mongdb集約クエリはパイプライン操作です。したがって、後続のクエリの結果は次のクエリに渡されます。 Mongodb集約の詳細については、thisを参照してください。間違いは、$groupクエリを使用したときに_idが次の$lookupクエリに渡されているということです。次のクエリを使用してこれを修正できます。

Answer.aggregate([ 
    {$unwind: "$_question"}, 
    {$match: {_poll: poll._id}}, 
    {$group: { 
     _id: '$_question', 
     _poll: { $first: '$_poll'}, 
     _user: { $first: '$_user'}, 
     _question : { $first: "$_question "} 
    }}, 
    { 
     $lookup : { 
     from : 'polls', 
     localField : '_poll', 
     foreignField: '_id', 
     as: 'poll' 
     }, 
    }, 
    { 
     $lookup : { 
     from : 'questions', 
     localField : '_question', 
     foreignField: '_id', 
     as: 'questions' 
     }, 
    }, 
    { 
     $lookup : { 
     from : 'users', 
     localField : '_user', 
     foreignField: '_id', 
     as: 'user' 
     }, 
    }, 
], function (err, result) { 
    res.status(200).json(result); 
}); 
関連する問題