[英]use for loop in node js?
我正在使用for循環從mongodb檢索數據並在瀏覽器中顯示它,但是它僅在第一次迭代時就停止了。 所以我只有第一個條目作為輸出。 而它在控制台日志中給出了正確的輸出。 請幫忙?
var movieSchema1 = new mongoose.Schema({
name:String,
address:String,
location:String
});
var user=mongoose.model('movie', movieSchema1, 'movie');
for (var i = 0; i < user.length; i++) {
res.json("iteration " + i);
res.json('name:' + user[i].name + user[i].address);
}
正如其他人所說的那樣,為您的響應建立一個對象,然后對它進行res.json()。 因為您嘗試發送一個數組,所以只需使用.map()來轉換每個數組:
//turn the array of users into the objects we want to send
const responseData = user.map( (movie, i) => {
return {
iteration: i,
name: movie.name + ' ' + movie.address
};
});
//this converts the array to a string for you
res.json( responseData );
您可以使用find()
方法從架構接收所有對象。
var response;
user.find({}, function(err, users){
if(err) throw err;
if(users.length != 0){
response = users.map((user, i) => {
return {
index: i,
name: user.name + ' ' + user.address
};
}
})
for(var i = 0; i < response.length; i++){
res.write('Key: ' i + ' the value: ' response[i] + '\n');
}
res.end();
您還應該只使用一次res.json()
,因為它將Can't set headers after they are sent
error Can't set headers after they are sent
返回返回Can't set headers after they are sent
。
請參閱此鏈接以獲取有關res.json()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.