私は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を使用しています。
ありがとうございます!
Github-Flavored Markdown(トリプルバッククック付きのコードセクション)はここでは機能しません。代わりに4つのスペースでコードセクションをインデントします(これにはエディタボタンもあります) – Tomalak