2017-01-18 15 views
1

私はmongooseの助けを借りてデータベースを作成しました。単一ドキュメントの参照を埋め込むのはうまくいきますが、配列を読み込むにはうまくいきません。マングース配列集団

私に迷惑を与えたモデルは、以下の通りである:

タスク

var taskSchema = new Schema({ 
    _client: { type: Schema.Types.ObjectId, ref: 'Client', required: true }, 
    link: { type: String, required: true }, 
    reqDate: { type: Date, default: Date.now }, 
    startDate: { type: Date }, 
    extId: { type: String, required: true }, 
    results: [{ type: Schema.Types.ObjectId, ref: 'Result' }] 
}); 
var Task = mongoose.model('Task', taskSchema); 

結果

var resultSchema = new Schema({ 
    _task: { type: Schema.Types.ObjectId, ref: 'Task', required: true }, 
    _module: { type: Schema.Types.ObjectId, ref: 'Module', required: true }, 
    finishDate: { type: Date, required: true }, 
    result: { type: Object, required: true } 
}); 
var Result = mongoose.model('Result', resultSchema); 

私は次のコードでデータベースに結果を追加してい:

let taskPromise = Task.findById(req.params.taskId).exec(); 
let modulePromise = Module.findOne({ name: req.body.module }).exec(); 

// Wait for promises to finish 
Promise.all([taskPromise, modulePromise]) 
    .then(values => { 
     if (values[1]) { 
      // Create new result and add to database 
      let result = new Result({ 
       _task: values[0], 
       _module: values[1], 
       finishDate: Date.now(), 
       result: req.body.result 
      }); 
      result.save(); 

      res.json({ result: 'success' }); 
     } else { 
      // If findOne does not find a result, it resolves the promise instead of rejecting it 
      // Therefore Promise.all is successful and we have to check for errors like this 
      res.json({ error: 'The module is invalid' }); 
     } 
     // findById on the other hand rejects a promise when it does not find a result 
     // That's why we are catching the error here. 
    }).catch(err => res.json({ error: 'The task is invalid' })); 

結果はAPI呼び出しで追加されます。要求は事前に検証されています。移入する

は、私は次のコードを使用しています:IDが

aswellハードコードされたよう

Task.findById('587f48ba009932409cf51626') 
     .populate('results _client').exec(function(err, task) { 
      res.json(task); 
     }); 

いけない心なしエラー処理がないことを、これは、単なるデバッグの理由からですデータベースがこのタスクの結果で満たされていても、_clientの母集団は正常に動作し、resultsはまだ空の配列です。

私はこのためdocumentationを追っていると、私のコードの違いを見ていないので、私は私が間違っているかもしれないものは考えています。この上

思考が大幅に

E/Iは、このタスクの結果が完全に正常に動作し、助成金、私は必要なすべての文書を取得するために

Result.find({_task: task}, function(err, result) { 
    console.dir(result); 
}) 

を使用してテスト

を高く評価しています。私はこれがまだエラーを見つけることができない参照との問題を呼び出すと思います。

答えて

-1
Task.findById('587f48ba009932409cf51626') 
     .populate('_client') 
     .populate('results') 
     .exec(function(err, task) { 
      res.json(task); 
     }) 
+0

mongoose 3.6以降では、複数回ポピュレートする必要はありません。このコードは基本的には私のものと同じです。 – Marv

関連する問題