我在尝试查找值抛出 2 模型时遇到问题
.get(function(req, res) {
var sellerPosts = [];
Product.find({seller_id : req.params.seller_id}, function(err, products) {
if (err) throw err;
for (var i = 0; i < products.length; i++) {
console.log("id", products[i].id);
Post.find({product_id : products[i].id}, function(err, posts) {
if (err) throw err;
for (var j = 0; j < posts.length; j++) {
sellerPosts.push(posts[j]);
console.log("in find",sellerPosts);
}
});
console.log(sellerPosts);
}
console.log("test", sellerPosts);
res.send(sellerPosts);
});
})
这是日志:
App listening on port 3000!
Connected to database
id 58ea96464429aa154cb8c43a
[]
id 58ed3171a0cc7f20f4c74c1c
[]
test []
in find [ { _id: 58ed28b8993a2317e41fc742,
product_id: 58ea96464429aa154cb8c43a,
phone: 9123123,
address: 'hanhitie17',
other: 'no others',
__v: 0 } ]
in find [ { _id: 58ed28b8993a2317e41fc742,
product_id: 58ea96464429aa154cb8c43a,
phone: 9123123,
address: 'hanhitie17',
other: 'no others',
__v: 0 },
{ _id: 58ed33cea0cc7f20f4c74c1d,
product_id: 58ed3171a0cc7f20f4c74c1c,
phone: 9123123,
address: 'hanhitie17',
other: 'no others',
__v: 0 } ]
第一个卖家帖子仍然打印出真实值,但"测试"日志为空。做一些日志后。我认为这是因为在 Product.find(( 中的第一个 for 之后,程序运行 res.send 然后运行 Post.find((。请帮我解决这个问题!!!
您在循环中调用Post.find
会导致问题,因为它是异步操作,您需要使其顺序化。您可以使用异步库执行此操作,如下面的代码所示。
.get(function(req, res) {
var sellerPosts = [];
Product.find({seller_id : req.params.seller_id}, function(err, products) {
if (err) throw err;
async.eachSeries(products, function(product, next){
Post.find({product_id : product.id}, function(err, posts) {
if (err) next(err);
for (var j = 0; j < posts.length; j++) {
sellerPosts.push(posts[j]);
console.log("in find",sellerPosts);
}
next(null);
});
}, function(err){
if(err) throw err;
res.send(sellerPosts);
})
});
})
是的,响应在Post.find
完成之前返回,这是正确的行为,因为javascript是异步的,你应该使用承诺
所以我用承诺重写了你的代码:
.get((req, res) => {
Product.find({ seller_id: req.params.seller_id })
.then(products => {
let postPromises = products.map(product => {
return Post.find({ product_id: product.id });
});
return Promise.all(postPromises);
})
.then(posts => {
let sellerPosts = Array.prototype.concat.apply([], posts);
res.json(sellerPosts);
})
.catch(err => {
throw err;
});
});