Reputation: 23
I am novice in nodejs and I want to populate the data using async-waterfall. Can anyone help me to fix the error of below code? I don't know where the actually error is occuring. It might be either in API or in model to referencing the object id.
API
router.get('/restaurentdetails',(req,res)=>{
waterfall([
function(callback){
var fk_user = Menu.fk_user;
Owner.find().then((ownerInfo)=>{
res.json(ownerInfo);
}).catch(err =>{
if(err){
throw err;
}
});
callback(null,fk_user);
},
function(fk_user,callback){
Menu.find(fk_user).then((menuInfo)=>{
res.json(menuInfo);
}).catch(err =>{
if(err){
throw err;
}
});
//callback(null,'end');
}
]),
function(err,result){
console.log('Main callback '+result);
}
});
model1:-Owner detail model
const mongoose = require('mongoose');
const ownerSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
phone: {
type: Number,
required: true
},
email: {
type: String,
required: true
},
});
module.exports = mongoose.model('ownerInfo', ownerSchema);
model2:-menu detail model
const mongoose = require('mongoose');
const menuSchema = new mongoose.Schema({
fk_user: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'ownerInfo'
}],
name: {
type: String,
required: true
},
price: {
type: Number,
required: true
}
});
module.exports = mongoose.model('menuInfo', menuSchema);
I am getting the following error:-
(node:6456) UnhandledPromiseRejectionWarning: Error
[ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at ServerResponse.setHeader (_http_outgoing.js:470:11)
at ServerResponse.header (A:\nodejs
demo\RestaurantNew\node_modules\express\lib\response.js:767:10)
at ServerResponse.json (A:\nodejs
demo\RestaurantNew\node_modules\express\lib\response.js:264:10)
at Menu.find.then (A:\nodejs
demo\RestaurantNew\controller\hotelController.js:59:21)
at process._tickCallback (internal/process/next_tick.js:68:7)
(node:6456) UnhandledPromiseRejectionWarning: Unhandled promise
rejection. This error originated either by throwing inside of an async
function without a catch block, or by rejecting a promise which was not
handled with .catch(). (rejection id: 1)
(node:6456) [DEP0018] DeprecationWarning: Unhandled promise rejections
are deprecated. In the future, promise rejections that are not handled
will terminate the Node.js process with a non-zero exit code.
Upvotes: 1
Views: 66
Reputation: 6117
The problem is you are trying to send two responses for the same request here in the waterfall method first response is sent res.json(ownerInfo)
; and for the same request you call res.json(menuInfo);
in the second function again What happens is that you are trying to send a response after it has already been sent. Try to send the result in only one function.
Upvotes: 1