【问题标题】:Node/Express.js - array elements are disappearingNode/Express.js - 数组元素正在消失
【发布时间】:2018-06-15 22:26:42
【问题描述】:

我正在尝试将数据库中的一些信息放入一个数组中,以便我可以继续使用它。但是,在 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);

【问题讨论】:

  • 你能发布玩具和相关架构吗。我可以帮助你摆脱奇怪的循环地狱

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


【解决方案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({});
    }
}

【讨论】:

  • lt 在控制台上打印出价格,我已经弄清楚了,但我实际上需要包含元素的数组,以便我可以继续使用它。 console.log 仅用于调试
猜你喜欢
  • 2015-12-27
  • 2017-09-13
  • 2011-03-12
  • 1970-01-01
  • 1970-01-01
  • 2023-03-15
  • 2022-11-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多