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