2016-12-11 17 views
0

のプロパティを設定することはできませんこんにちは、私は私が通過しようとすると、この中で、私はマングースエラーが未定義

router.post('/query',function(req,res,next){ 
    if (req.body){ 
     var result=[]; 
     console.log(req.body.filters); 
     Pollee.find(req.body.filters) 
     .select('id age birthday user') 
     .populate('user','email') 
     .lean(true) 
     .exec(function(err,pollees){ 
      if(err) { 
       console.log(err); 
       return next(err); 
      } 
      for (var i = 0; i < pollees.length; i++){    
      var query = test(pollees[i]._id); 
      query.exec(function(err,inters){ 
       if(err) 
        return console.log(err); 
       inters.forEach(function(inter){ 
        pollees[i].interaction = inter; 
       }); 
      }); 
      } 
      res.json(pollees);  
      }; 
     }) 
    } 
}); 

function test(id){ 
    var promise = Interaction.find({pollee:id}).select('status other'); 
    return promise; 
} 

ここに私の問題そのInteraction.findのある検索クエリを実現する、Node.jsの中でこのコードを持っていますpollees [i]に関するこのクエリの結果.interaction = inter;コンソールが私にエラーを設定しました

プロパティpollees [i] .interaction = inter;を設定できません。定義されていない

私は

var interactionSchema = new Schema({ 
    pollee: { type: ObjectId, ref: 'Pollee' }, 
    answers: { type: [ObjectId], ref: 'Answer', autopopulate: true }, 
    status: type: String 
}); 

var PolleeSchema = new Schema({ 
    firstName: String, 
    lastName: String, 
    gender: String, 
    user: { type: ObjectId, ref: 'User', required: true }, 
    interactions: { type: [ObjectId], ref: 'Interaction', autopopulate: true } 
}); 

var userSchema = new Schema({ 
    email: String, 
    pollee: { type: Schema.Types.ObjectId, ref: 'Pollee', autopopulate: true } 
}); 

どうもありがとうを使用したモデル!

答えて

0

私はこの問題に次のことを言うと思います:あなたのコードのforサイクルであなたは、非同期メソッドquery.exec()を呼んでいます。コールバックが実行されるまでに、サイクルはすでに終了しており、値はi === pollees.lengthです。したがってpollees[i]は存在しない配列要素(未定義)を指しており、プロパティーを設定しようとすると "undefinedのプロパティーを設定できません"というエラーが表示されますinteraction。 これは.bindを使用することです解決する方法の1つに:

query.exec(function(i, err,inters){ //i is among the params in your callback 
    if(err) 
     return console.log(err); 
    inters.forEach(function(inter){ 
     pollees[i].interaction = inter; 
    }); 
}.bind(null, i)); //you're binding the variable 'i' to the callback 

EDIT:

そしてres.json(pollees);が動作するためには(別の問題である)あなたがPromiseにすべてのコールバックをラップする必要があります。これはおそらく、このようなもののようになります。

var queries = []; //an array of promises 
for (var i = 0; i < pollees.length; i++){    
    queries.push(test(pollees[i]._id)); //add a promise to the array 
} 
//wait for all promises to resolve 
Promise.all(queries).then(function(results) { 
    results.forEach(function(inter, index){ 
     pollees[index].interaction = inter; 
    }); 
    res.json(pollees); //return response 
}); 
+0

作品が、polleesの相互作用のフィールドなしで返さ – ZizouJd

+0

確認、コールバックが – anytimecoder

+0

が同様にその問題のために私の答えを更新し、実行を取得する前に応答を返すしているので、 – anytimecoder

関連する問題