我在 mongodb 中有一个 Collection,其中包含嵌入的引用文档,这迫使我运行多个匿名函数。
首先我初始化这个数组
var player = {
name : '',
life : 10,
gold : 50,
score : 0,
clientId : socket.id,
playerId : data.playerId,
deck : []
};
现在我需要通过从 mongodb 获取数据来添加数据。
// First find the player.
var playerCol = db.collection('Guest');
playerCol.find({'_id' : new ObjectId(data.playerId)}).toArray(function(err, playerRes) {
// Traverse and load each tower in deck.
// Traverse each embedded reference, so each can be fetched.
playerRes[0].deck.towers.forEach(function(tower) {
// fetch data for tower.
towerCol = db.collection('Tower');
towerCol.find({'_id' : new ObjectId(tower.oid)}).toArray(function(err, completeTower) {
// Add the tower data to the deck.
player.deck.push(completeTower.pop());
});
});
现在的问题是播放器数组仍然是第一次初始化时的样子。为什么我在播放器中的数据不持久?好吧,我知道为什么,因为当不在匿名函数中调用时,它在另一个范围内。但是我应该如何将我的值添加到播放器数组中?
片段合二为一。
// Initialize the player.
var player = {
name : '',
life : 10,
gold : 50,
score : 0,
clientId : socket.id,
playerId : data.playerId,
deck : []
};
// Load players deck.
var playerCol = db.collection('Guest');
playerCol.find({'_id' : new ObjectId(data.playerId)}).toArray(function(err, playerRes) {
// Traverse and load each tower in deck.
playerRes[0].deck.towers.forEach(function(tower) {
towerCol = db.collection('Tower');
towerCol.find({'_id' : new ObjectId(tower.oid)}).toArray(function(err, completeTower) {
player.name = "Melvar";
player.deck.push(completeTower.pop());
console.log(player.deck); // Prints the data, just pushed
});
});
console.log(player.deck); // Prints empty array.
process.exit(1);