2015-08-21 85 views
0

我已經調用了lean()來確保我已將返回的數據轉換爲普通對象,但只有故事[x] .authorId不會作爲屬性添加到當前故事[x]對象。如何修改從Mongoose查詢返回的數據?

有人可以解釋爲什麼並提供解決方案嗎?它是否與範圍有關,還是我無法修改另一個查詢中的對象?

Story.find({}).sort({created: -1}).lean().exec(function(err, stories) { 
    if (err) throw err; 
    for(var x=0; x < stories.length; x++) { 
     stories[x].commentsLength = stories[x].comments.length; 
     stories[x].created = stories[x]._id.getTimestamp(); 
     stories[x].timeAgo = timeHandler(stories[x]); 
     User.find({'username': stories[x].author}).lean().exec(function(x, err, data) { 
      stories[x].authorId = data[0]._id; 
       console.log(stories[x]); // authorId is there 
     }.bind(this, x)); 
     console.log(stories[x]); // authorId is not there 
    } 
    res.render('news', {message: "Homepage", data: stories}); 
}) 

回答

0

它看起來對我說,你想註銷stories[x]調用異步User.find()功能之後。因爲User.find()異步運行,所以在調用完成之前您將無法訪問其結果。換句話說,這是預期的行爲。

別的東西注意,你可能會發現你的代碼是比較容易,如果你使用一個迭代函數像.forEach甚至async.each模塊讀取:如果你試圖修改返回

Story.find({}).sort({created: -1}).lean().exec(function(err, stories) { 
    if (err) throw err; 
    stories.forEach(function(story) { 
     story.commentsLength = story.comments.length; 
     story.created = story._id.getTimestamp(); 
     story.timeAgo = timeHandler(story); 
     User.find({ 
      'username': story.author 
     }).lean().exec(function(x, err, data) { 
      story.authorId = data[0]._id; 
      console.log(story); // authorId is there, because this means User.find completed 
     }.bind(this, x)); 
     console.log(story); // authorId is not there, and never will be, because this function executes before User.find completes its lookup 
    }); 
    res.render('news', { 
     message: "Homepage", 
     data: stories 
    }); 
}); 

數據,您可以使用異步以確保在執行回調之前完成所有查找功能:

function getStory(callback) { 
    Story.find({}).sort({created: -1}).lean().exec(function(err, stories) { 
     if (err) throw err; 
     async.each(stories, function(story, callback) { 
      story.commentsLength = story.comments.length; 
      story.created = story._id.getTimestamp(); 
      story.timeAgo = timeHandler(story); 
      User.find({ 
       'username': story.author 
      }).lean().exec(function(x, err, data) { 
       story.authorId = data[0]._id; 
       callback(err, story); 
      }.bind(this, x)); 
     }, function(err, results) { 
      callback(err, results); // results is now an array of modified stories 
     }); 
     res.render('news', { 
      message: "Homepage", 
      data: stories 
     }); 
    }) 
}