How to send headers after loophow to save multiple for loops data?How do I debug Node.js applications?How do I get started with Node.jsHow do I get the path to the current script with Node.js?How do I pass command line arguments to a Node.js program?How to decide when to use Node.js?How to exit in Node.jsWhat is the purpose of Node.js module.exports and how do you use it?How can I update NodeJS and NPM to the next versions?Error: Can't set headers after they are sent to the clientHow do I update each dependency in package.json to the latest version?

Do UK voters know if their MP will be the Speaker of the House?

Valid term from quadratic sequence?

When (not how or why) to calculate Big O of an algorithm

What do you call someone who asks many questions?

Examples of smooth manifolds admitting inbetween one and a continuum of complex structures

Can compressed videos be decoded back to their uncompresed original format?

Is there a hemisphere-neutral way of specifying a season?

Method Does Not Exist error message

Are there any examples of a variable being normally distributed that is *not* due to the Central Limit Theorem?

Would Slavery Reparations be considered Bills of Attainder and hence Illegal?

Can my sorcerer use a spellbook only to collect spells and scribe scrolls, not cast?

Unlock My Phone! February 2018

If human space travel is limited by the G force vulnerability, is there a way to counter G forces?

Madden-Julian Oscillation (MJO) - How to interpret the index?

CAST throwing error when run in stored procedure but not when run as raw query

Plagiarism or not?

What method can I use to design a dungeon difficult enough that the PCs can't make it through without killing them?

Could the museum Saturn V's be refitted for one more flight?

Avoiding the "not like other girls" trope?

I would say: "You are another teacher", but she is a woman and I am a man

Short story with a alien planet, government officials must wear exploding medallions

Is it logically or scientifically possible to artificially send energy to the body?

How to tell a function to use the default argument values?

Mathematica command that allows it to read my intentions



How to send headers after loop


how to save multiple for loops data?How do I debug Node.js applications?How do I get started with Node.jsHow do I get the path to the current script with Node.js?How do I pass command line arguments to a Node.js program?How to decide when to use Node.js?How to exit in Node.jsWhat is the purpose of Node.js module.exports and how do you use it?How can I update NodeJS and NPM to the next versions?Error: Can't set headers after they are sent to the clientHow do I update each dependency in package.json to the latest version?













0















I want to do find an user, whose model contains an array of cities (for example:[Madrid, London, Moscow, Buenos Aires, etc])



This is the model:



var UserSchema = Schema(
name: String,
surname: String,
userName: String,
email: String,
password: String,
rol: String,
suscriptionDate: Date,
cities:[String],
citiesPopulate:[]
);


Once I've found the user, I want to iterate through this array to use each city as the parameter in order to find the info that I have on the model City just to add coords to user.citiesPopulate



function findUsersCities(req,res)
let id=req.body._id;

User.findById(id,function(err,userFound)
if(err)
console.log(err)
else

for(let i=0;i<userFound.cities.length;i++)

City.findOne('city':userFound.cities[i],function(err,citiesFound)
if(err)
console.log(err)
else
userFound.citiesPopulate.push(citiesFound.coords);
console.log(userFound)

)



)



And, once all the info of every single city has been added to userFound.citiesPopulate (by now just arrays with a pair of coordinates), I want to use res.status(200).send(userFound) to see the result on my postman console, something like this(three cities and three pairs of coordinates):



 cities: [ 'Bilbao', 'Madrid', 'Barcelona' ],
citiesPopulate: [ [ -3.68, 40.4 ], [ -2.97, 43.25 ], [ 2.18, 41.38 ] ],
_id: 5c82c2e5cfa8d543d0133dd6,
name: 'pruebas35',
surname: 'pruebas35',
userName: 'pruebas35',
email: 'pruebas35@prueba.es',
password: '$2a$10$eSue5gw7r4dFPtwD8qzJhODcvvNFaRkeQYRAOPO9MCBsy3Djhkffq',
rol: 'user',
suscriptionDate: 2019-03-08T19:30:45.075Z,
__v: 0


But if I type the res.status into the loop, it is sent and I can´t get the whole information.



I'd like to know a solution for this, please.










share|improve this question






















  • If I use a callback function after the first query, the one that finds the user by Id, I get an error that says:TypeError: Invalid select() argument. Must be string or object. But the argument is actually a parameter

    – Carlos FTG
    Mar 9 at 11:26















0















I want to do find an user, whose model contains an array of cities (for example:[Madrid, London, Moscow, Buenos Aires, etc])



This is the model:



var UserSchema = Schema(
name: String,
surname: String,
userName: String,
email: String,
password: String,
rol: String,
suscriptionDate: Date,
cities:[String],
citiesPopulate:[]
);


Once I've found the user, I want to iterate through this array to use each city as the parameter in order to find the info that I have on the model City just to add coords to user.citiesPopulate



function findUsersCities(req,res)
let id=req.body._id;

User.findById(id,function(err,userFound)
if(err)
console.log(err)
else

for(let i=0;i<userFound.cities.length;i++)

City.findOne('city':userFound.cities[i],function(err,citiesFound)
if(err)
console.log(err)
else
userFound.citiesPopulate.push(citiesFound.coords);
console.log(userFound)

)



)



And, once all the info of every single city has been added to userFound.citiesPopulate (by now just arrays with a pair of coordinates), I want to use res.status(200).send(userFound) to see the result on my postman console, something like this(three cities and three pairs of coordinates):



 cities: [ 'Bilbao', 'Madrid', 'Barcelona' ],
citiesPopulate: [ [ -3.68, 40.4 ], [ -2.97, 43.25 ], [ 2.18, 41.38 ] ],
_id: 5c82c2e5cfa8d543d0133dd6,
name: 'pruebas35',
surname: 'pruebas35',
userName: 'pruebas35',
email: 'pruebas35@prueba.es',
password: '$2a$10$eSue5gw7r4dFPtwD8qzJhODcvvNFaRkeQYRAOPO9MCBsy3Djhkffq',
rol: 'user',
suscriptionDate: 2019-03-08T19:30:45.075Z,
__v: 0


But if I type the res.status into the loop, it is sent and I can´t get the whole information.



I'd like to know a solution for this, please.










share|improve this question






















  • If I use a callback function after the first query, the one that finds the user by Id, I get an error that says:TypeError: Invalid select() argument. Must be string or object. But the argument is actually a parameter

    – Carlos FTG
    Mar 9 at 11:26













0












0








0








I want to do find an user, whose model contains an array of cities (for example:[Madrid, London, Moscow, Buenos Aires, etc])



This is the model:



var UserSchema = Schema(
name: String,
surname: String,
userName: String,
email: String,
password: String,
rol: String,
suscriptionDate: Date,
cities:[String],
citiesPopulate:[]
);


Once I've found the user, I want to iterate through this array to use each city as the parameter in order to find the info that I have on the model City just to add coords to user.citiesPopulate



function findUsersCities(req,res)
let id=req.body._id;

User.findById(id,function(err,userFound)
if(err)
console.log(err)
else

for(let i=0;i<userFound.cities.length;i++)

City.findOne('city':userFound.cities[i],function(err,citiesFound)
if(err)
console.log(err)
else
userFound.citiesPopulate.push(citiesFound.coords);
console.log(userFound)

)



)



And, once all the info of every single city has been added to userFound.citiesPopulate (by now just arrays with a pair of coordinates), I want to use res.status(200).send(userFound) to see the result on my postman console, something like this(three cities and three pairs of coordinates):



 cities: [ 'Bilbao', 'Madrid', 'Barcelona' ],
citiesPopulate: [ [ -3.68, 40.4 ], [ -2.97, 43.25 ], [ 2.18, 41.38 ] ],
_id: 5c82c2e5cfa8d543d0133dd6,
name: 'pruebas35',
surname: 'pruebas35',
userName: 'pruebas35',
email: 'pruebas35@prueba.es',
password: '$2a$10$eSue5gw7r4dFPtwD8qzJhODcvvNFaRkeQYRAOPO9MCBsy3Djhkffq',
rol: 'user',
suscriptionDate: 2019-03-08T19:30:45.075Z,
__v: 0


But if I type the res.status into the loop, it is sent and I can´t get the whole information.



I'd like to know a solution for this, please.










share|improve this question














I want to do find an user, whose model contains an array of cities (for example:[Madrid, London, Moscow, Buenos Aires, etc])



This is the model:



var UserSchema = Schema(
name: String,
surname: String,
userName: String,
email: String,
password: String,
rol: String,
suscriptionDate: Date,
cities:[String],
citiesPopulate:[]
);


Once I've found the user, I want to iterate through this array to use each city as the parameter in order to find the info that I have on the model City just to add coords to user.citiesPopulate



function findUsersCities(req,res)
let id=req.body._id;

User.findById(id,function(err,userFound)
if(err)
console.log(err)
else

for(let i=0;i<userFound.cities.length;i++)

City.findOne('city':userFound.cities[i],function(err,citiesFound)
if(err)
console.log(err)
else
userFound.citiesPopulate.push(citiesFound.coords);
console.log(userFound)

)



)



And, once all the info of every single city has been added to userFound.citiesPopulate (by now just arrays with a pair of coordinates), I want to use res.status(200).send(userFound) to see the result on my postman console, something like this(three cities and three pairs of coordinates):



 cities: [ 'Bilbao', 'Madrid', 'Barcelona' ],
citiesPopulate: [ [ -3.68, 40.4 ], [ -2.97, 43.25 ], [ 2.18, 41.38 ] ],
_id: 5c82c2e5cfa8d543d0133dd6,
name: 'pruebas35',
surname: 'pruebas35',
userName: 'pruebas35',
email: 'pruebas35@prueba.es',
password: '$2a$10$eSue5gw7r4dFPtwD8qzJhODcvvNFaRkeQYRAOPO9MCBsy3Djhkffq',
rol: 'user',
suscriptionDate: 2019-03-08T19:30:45.075Z,
__v: 0


But if I type the res.status into the loop, it is sent and I can´t get the whole information.



I'd like to know a solution for this, please.







node.js mongoose






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 8 at 22:20









Carlos FTGCarlos FTG

134




134












  • If I use a callback function after the first query, the one that finds the user by Id, I get an error that says:TypeError: Invalid select() argument. Must be string or object. But the argument is actually a parameter

    – Carlos FTG
    Mar 9 at 11:26

















  • If I use a callback function after the first query, the one that finds the user by Id, I get an error that says:TypeError: Invalid select() argument. Must be string or object. But the argument is actually a parameter

    – Carlos FTG
    Mar 9 at 11:26
















If I use a callback function after the first query, the one that finds the user by Id, I get an error that says:TypeError: Invalid select() argument. Must be string or object. But the argument is actually a parameter

– Carlos FTG
Mar 9 at 11:26





If I use a callback function after the first query, the one that finds the user by Id, I get an error that says:TypeError: Invalid select() argument. Must be string or object. But the argument is actually a parameter

– Carlos FTG
Mar 9 at 11:26












1 Answer
1






active

oldest

votes


















1














As pointed out by Carlos, this won't work because of the asynchronous nature of database requests. The way I would do it is to use async/await to make the code synchronous, like this:



function findUsersCities(req,res)
let id=req.body._id;

User.findById(id,async function(err,userFound)
if(err)
console.log(err)
else
try

for(let i=0;i<userFound.cities.length;i++)

let cityFound = await City.findOne('city':userFound.cities[i]);

userFound.citiesPopulate.push(cityFound.coords);


//complete userFound
console.log(userFound);

catch (e)
console.log(e);



)



Notice the use of the keyword async in the callback function from User.findById. You can only use the await feature if it is inside a function marked with the async keyword.



Also, when you doesn't specify a callback function to any Mongoose query funcion, it returns a Promise, and you can only use the await keyword on promises.



If the promise resolves, the code will continue to run, and the resolved value will be in the variable cityFound, otherwise (if the promise rejects), it will throw an execption, so the code will fall into the catch statement, and the rejected value will be in variable e.






share|improve this answer

























  • This is what I did first but the problem is that it returns the coords array empty as this is asynchronus, and it deals faster with res.status(200).send(userFound) rather than the for loop, I guess

    – Carlos FTG
    Mar 9 at 10:57











  • You are correct, my apologies. Edited the answer, check if it helps you now.

    – Renato Vassão
    Mar 9 at 13:48











  • That's fine, know it works, thanks Renato.

    – Carlos FTG
    Mar 10 at 17:36











  • Great! Could you please accept the answer?

    – Renato Vassão
    Mar 10 at 18:11











Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55071803%2fhow-to-send-headers-after-loop%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









1














As pointed out by Carlos, this won't work because of the asynchronous nature of database requests. The way I would do it is to use async/await to make the code synchronous, like this:



function findUsersCities(req,res)
let id=req.body._id;

User.findById(id,async function(err,userFound)
if(err)
console.log(err)
else
try

for(let i=0;i<userFound.cities.length;i++)

let cityFound = await City.findOne('city':userFound.cities[i]);

userFound.citiesPopulate.push(cityFound.coords);


//complete userFound
console.log(userFound);

catch (e)
console.log(e);



)



Notice the use of the keyword async in the callback function from User.findById. You can only use the await feature if it is inside a function marked with the async keyword.



Also, when you doesn't specify a callback function to any Mongoose query funcion, it returns a Promise, and you can only use the await keyword on promises.



If the promise resolves, the code will continue to run, and the resolved value will be in the variable cityFound, otherwise (if the promise rejects), it will throw an execption, so the code will fall into the catch statement, and the rejected value will be in variable e.






share|improve this answer

























  • This is what I did first but the problem is that it returns the coords array empty as this is asynchronus, and it deals faster with res.status(200).send(userFound) rather than the for loop, I guess

    – Carlos FTG
    Mar 9 at 10:57











  • You are correct, my apologies. Edited the answer, check if it helps you now.

    – Renato Vassão
    Mar 9 at 13:48











  • That's fine, know it works, thanks Renato.

    – Carlos FTG
    Mar 10 at 17:36











  • Great! Could you please accept the answer?

    – Renato Vassão
    Mar 10 at 18:11















1














As pointed out by Carlos, this won't work because of the asynchronous nature of database requests. The way I would do it is to use async/await to make the code synchronous, like this:



function findUsersCities(req,res)
let id=req.body._id;

User.findById(id,async function(err,userFound)
if(err)
console.log(err)
else
try

for(let i=0;i<userFound.cities.length;i++)

let cityFound = await City.findOne('city':userFound.cities[i]);

userFound.citiesPopulate.push(cityFound.coords);


//complete userFound
console.log(userFound);

catch (e)
console.log(e);



)



Notice the use of the keyword async in the callback function from User.findById. You can only use the await feature if it is inside a function marked with the async keyword.



Also, when you doesn't specify a callback function to any Mongoose query funcion, it returns a Promise, and you can only use the await keyword on promises.



If the promise resolves, the code will continue to run, and the resolved value will be in the variable cityFound, otherwise (if the promise rejects), it will throw an execption, so the code will fall into the catch statement, and the rejected value will be in variable e.






share|improve this answer

























  • This is what I did first but the problem is that it returns the coords array empty as this is asynchronus, and it deals faster with res.status(200).send(userFound) rather than the for loop, I guess

    – Carlos FTG
    Mar 9 at 10:57











  • You are correct, my apologies. Edited the answer, check if it helps you now.

    – Renato Vassão
    Mar 9 at 13:48











  • That's fine, know it works, thanks Renato.

    – Carlos FTG
    Mar 10 at 17:36











  • Great! Could you please accept the answer?

    – Renato Vassão
    Mar 10 at 18:11













1












1








1







As pointed out by Carlos, this won't work because of the asynchronous nature of database requests. The way I would do it is to use async/await to make the code synchronous, like this:



function findUsersCities(req,res)
let id=req.body._id;

User.findById(id,async function(err,userFound)
if(err)
console.log(err)
else
try

for(let i=0;i<userFound.cities.length;i++)

let cityFound = await City.findOne('city':userFound.cities[i]);

userFound.citiesPopulate.push(cityFound.coords);


//complete userFound
console.log(userFound);

catch (e)
console.log(e);



)



Notice the use of the keyword async in the callback function from User.findById. You can only use the await feature if it is inside a function marked with the async keyword.



Also, when you doesn't specify a callback function to any Mongoose query funcion, it returns a Promise, and you can only use the await keyword on promises.



If the promise resolves, the code will continue to run, and the resolved value will be in the variable cityFound, otherwise (if the promise rejects), it will throw an execption, so the code will fall into the catch statement, and the rejected value will be in variable e.






share|improve this answer















As pointed out by Carlos, this won't work because of the asynchronous nature of database requests. The way I would do it is to use async/await to make the code synchronous, like this:



function findUsersCities(req,res)
let id=req.body._id;

User.findById(id,async function(err,userFound)
if(err)
console.log(err)
else
try

for(let i=0;i<userFound.cities.length;i++)

let cityFound = await City.findOne('city':userFound.cities[i]);

userFound.citiesPopulate.push(cityFound.coords);


//complete userFound
console.log(userFound);

catch (e)
console.log(e);



)



Notice the use of the keyword async in the callback function from User.findById. You can only use the await feature if it is inside a function marked with the async keyword.



Also, when you doesn't specify a callback function to any Mongoose query funcion, it returns a Promise, and you can only use the await keyword on promises.



If the promise resolves, the code will continue to run, and the resolved value will be in the variable cityFound, otherwise (if the promise rejects), it will throw an execption, so the code will fall into the catch statement, and the rejected value will be in variable e.







share|improve this answer














share|improve this answer



share|improve this answer








edited Mar 9 at 15:11

























answered Mar 8 at 22:58









Renato VassãoRenato Vassão

915




915












  • This is what I did first but the problem is that it returns the coords array empty as this is asynchronus, and it deals faster with res.status(200).send(userFound) rather than the for loop, I guess

    – Carlos FTG
    Mar 9 at 10:57











  • You are correct, my apologies. Edited the answer, check if it helps you now.

    – Renato Vassão
    Mar 9 at 13:48











  • That's fine, know it works, thanks Renato.

    – Carlos FTG
    Mar 10 at 17:36











  • Great! Could you please accept the answer?

    – Renato Vassão
    Mar 10 at 18:11

















  • This is what I did first but the problem is that it returns the coords array empty as this is asynchronus, and it deals faster with res.status(200).send(userFound) rather than the for loop, I guess

    – Carlos FTG
    Mar 9 at 10:57











  • You are correct, my apologies. Edited the answer, check if it helps you now.

    – Renato Vassão
    Mar 9 at 13:48











  • That's fine, know it works, thanks Renato.

    – Carlos FTG
    Mar 10 at 17:36











  • Great! Could you please accept the answer?

    – Renato Vassão
    Mar 10 at 18:11
















This is what I did first but the problem is that it returns the coords array empty as this is asynchronus, and it deals faster with res.status(200).send(userFound) rather than the for loop, I guess

– Carlos FTG
Mar 9 at 10:57





This is what I did first but the problem is that it returns the coords array empty as this is asynchronus, and it deals faster with res.status(200).send(userFound) rather than the for loop, I guess

– Carlos FTG
Mar 9 at 10:57













You are correct, my apologies. Edited the answer, check if it helps you now.

– Renato Vassão
Mar 9 at 13:48





You are correct, my apologies. Edited the answer, check if it helps you now.

– Renato Vassão
Mar 9 at 13:48













That's fine, know it works, thanks Renato.

– Carlos FTG
Mar 10 at 17:36





That's fine, know it works, thanks Renato.

– Carlos FTG
Mar 10 at 17:36













Great! Could you please accept the answer?

– Renato Vassão
Mar 10 at 18:11





Great! Could you please accept the answer?

– Renato Vassão
Mar 10 at 18:11



















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55071803%2fhow-to-send-headers-after-loop%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Thal And Out Agency railway station See also References External links Navigation menuOfficial Web Site of Pakistan RailwaysArchivedOfficial Web Site of Pakistan Railwayseeexpanding ite

Understanding generators in Python2019 Community Moderator ElectionGenerator function not working pythonFor loop not executing two timesGenerators - Printing generated valuesWhy can a python generator only be used once?What exactly do generators do?What does the “yield” keyword do?What does “list comprehension” mean? How does it work and how can I use it?sklearn Kfold acces single fold instead of for loopIs a generator the callable? Which is the generator?Apply Border To Range Of Cells Using OpenpyxlCalling an external command in PythonWhat are metaclasses in Python?What is the difference between @staticmethod and @classmethod?Finding the index of an item given a list containing it in PythonDifference between append vs. extend list methods in PythonHow can I safely create a nested directory in Python?Does Python have a ternary conditional operator?Understanding slice notationUnderstanding Python super() with __init__() methodsDoes Python have a string 'contains' substring method?

How can I change the color of pagination dots of UIPageControl?How to change UIPageControl dotsIs there a way to change page indicator dots colorCustomize dot with image of UIPageControl at index 0 of UIPageControlNo visible @interface for 'NSObject<PageControlDelegate>' declares the selector 'pageControlPageDidChange:'How to change the color of pagination dots in UIPageControl with a different color per pagepagecontrol indicator custom image instead of DefaultChanging the colour of UIPageControl dots in MonoTouchpagecontrol selectable page visibility color?Alternative way to load ViewControllers on a UIPageControlHow to set only layer.border-color for UIpage control dots in swiftHow can I develop for iPhone using a Windows development machine?How to change the name of an iOS app?UITableView - change section header coloruipagecontrol indicator(dot)issueCustom UIPageControl dots color not changingchange the interspace between UIPageControl dotsHow to change Status Bar text color in iOSHow can I change image tintColor in iOS and WatchKitUIPageControl dots with larger space in between each dotsHow to change the color of pagination dots in UIPageControl with a different color per page