Node / Express.js - 数组元素正在消失

时间:2018-01-06 06:40:22

标签: javascript arrays node.js express web-development-server

我试图将一些数据库中的信息放入数组中,以便我可以继续使用它。但是,在for循环中添加元素后,它们会消失并返回一个空数组。

// PROBLEM: all_prices-elements disappear TODO
// creates a price list

var all_prices = []; // all the prices
for (var i=0; i<query_id_list.length; i++) {
    if (Object.keys(query_id_list[i]).length != 0) {
        Toy.find(query_id_list[i], (err, toys) => {
            if (!err) {
                for (var i=0; i<toys.length; i++) {
                    var toyPrice = toys[i].price;
                    all_prices.push(toyPrice);
                }
            } else {
                res.json({});
            }
      });
    } else {
    res.json({});
    }
}

console.log(all_prices); // returns []

这是玩具架构:

var mongoose = require('mongoose');

// note: your host/port number may be different!
mongoose.connect('mongodb://localhost:27017/myDatabase');

var Schema = mongoose.Schema;

var toySchema = new Schema( {
    id: {type: String, required: true, unique: true},
    name: {type: String, required: true},
    price: Number
});

module.exports = mongoose.model('Toy', toySchema);

1 个答案:

答案 0 :(得分:1)

您需要将console.log置于mongoose查询

的回调中

此代码

var all_prices = []; // all the prices

for (var i=0; i<query_id_list.length; i++) {
if (Object.keys(query_id_list[i]).length != 0) {
    Toy.find(query_id_list[i], (err, toys) => {
        if (!err) {
            for (var i=0; i<toys.length; i++) {
                var toyPrice = toys[i].price;
                all_prices.push(toyPrice);
            }
        } else {
            res.json({});
        }
  });
} else {
  res.json({});
 }
}
console.log(all_prices); // returns []

// creates a price list

var all_prices = []; // all the prices
for (var i=0; i<query_id_list.length; i++) {
    if (Object.keys(query_id_list[i]).length != 0) {
        Toy.find(query_id_list[i], (err, toys) => {
            if (!err) {
                for (var i=0; i<toys.length; i++) {
                    var toyPrice = toys[i].price;
                    all_prices.push(toyPrice);
                }
              console.log(all_prices); // returns all_prices
            } else {
                res.json({});
            }
      });
    } else {
    res.json({});
    }
}