the first console log is getting logged but the second one isn't
and the catch is catching an error which I do not understand ...
this is my route:
router.post("/buy", JwtAuthenticateToken, async (req, res, next) => {
try {
const entry = new PositionModel(req.body)
console.log("new", entry)
const result = await entry.save()
console.log("saved", result)
} catch (error) {
console.log(error)
next(error)
}
})
this is what gets printed in the console:
new {
_id: 6125514a26fb7d06603b1a5a,
stock: 'Apple Inc',
ticker: 'AAPL',
purchasePrice: 149.62,
shares: 1,
owner: 6124e2a70d195a05f4e480cd
}
[Function: ErrorCtor]
I was passing an error to an error creator in my .post("validate")
probably the dumbest 5 lines of code I have ever written.
post("validate", (error, doc, next) => {
if (error) {
const err = createError(400, error)
next(err)
} else {
next(error)
}
})
Related
I am going to use vonage for text service.
However, only node.js syntax exists, and the corresponding API is being used.
There is a phenomenon that the callback is executed later when trying to receive the values returned from the callback to check for an error.
How can I solve this part? The code is below.
await vonage.message.sendSms(from, to, text, async (err, responseData) => {
if (err) {
console.log('1');
result.message = err;
} else {
if (responseData.messages[0]['status'] === '0') {
console.log('2');
} else {
console.log('3');
result.error = `Message failed with error: ${responseData.messages[0]['error-text']}`;
}
}
});
console.log(result);
return result;
When an error occurs as a result of executing the above code,
result{error:undefined}
3
Outputs are in order.
From what I can understand the issue is that you are passing a async callback. you could simply just give vonage.message.sendSms() a synchronous callback like so.
const result = {};
vonage.message.sendSms(from, to, text, (err, responseData) => {
if (err) {
console.log('1');
result.message = err;
} else {
if (responseData.messages[0]['status'] === '0') {
console.log('2');
} else {
console.log('3');
result.error = `Message failed with error: ${responseData.messages[0]['error-text']}`;
}
}
});
if you want to use async or promises I would suggest something like this
const sendSMS = (from, to, text) => new Promise( (resolve, reject) => {
vonage.message.sendSms(from, to, text, (err, responseData) => {
if (err) {
reject(err);
} else {
resolve(responseData);
}
});
});
// elsewhere
sendSMS(from, to, text)
.then(...)
.catch(...);
I am having issues storing a value in mongodb to a variable to use within my webpage.
When the user fills out a form on my website, I am trying to figure out what the arrivalTrailer was when the user filled out the arrival form.
So far I have
function previousLoad(loadNumber, callback){
CheckCall.find({loadNumber: loadNumber}).sort({date: 'desc'}).limit(1), function(err, arrival){
if (err){
callback(err, null);
}
else {
callback(null, arrival[0]);
}
}};
previousLoad(loadNumber, function(err, arrival){
if (err){
console.log(err);
}
else{
arrivalTrailer = arrival;
console.log(arrival);
}
});
console.log(previousLoad.arrival);
console.log(arrivalTrailer);
Both output as undefined when I try to console.log the variables.
Thank you :D
Try this :
async function previousLoad(loadNumber) {
try {
let resp = await CheckCall.find({ loadNumber: loadNumber }).sort({ date: -1 }).limit(1)
return resp[0]
} catch (error) {
console.log('error ::', error)
throw new Error (error)
}
}
/** You can return response from previousLoad but to test it, Call it from here */
previousLoad(loadNumber).then(resp => { console.log('successfully found ::', resp)}).catch(err => { console.log('Error in DB Op ::', err)});
Unable to store value outside of callback scope
I have tried declaring an array, an object and an empty variable outside of the callback scope and nothing is working.
router.post('/login', async (req, res, next) => {
try {
const user = await users.view('viewEmailandPassword', 'email', {keys: [`${req.body.email}`], include_docs: true},
function(err, body) {
if (!err) {
body.rows.forEach(function(doc) {
console.log(doc.value)
// return doc.value
});
}
});
console.log(user) <--- nothing is returned
}
catch(err){
next(err)
console.err(err, "this is the error")
}
})
I get an output of "undefined"
The problem here is that you're trying to use callback + promises. You need to either choose one or the other.
Here's the implementation using Promises (with async/await)
router.post('/login', async (req, res, next) => {
try {
const body = await users.view('viewEmailandPassword', 'email', {keys: [`${req.body.email}`], include_docs: true});
// Prints all the row values
body.rows.forEach(doc => console.log(doc.value));
// Let's say you want the first row
if(body.rows.length > 0){
console.log(body.rows[0].value);
} else {
console.log("Not value returned from the view");
}
}
catch(err){
next(err)
console.err(err, "this is the error")
}
})
I am trying to figure out why I am getting
console.log(removedEvent.invitees[i]) result:
luke231#gmail.com
yoda231#gmail.com
[Function: toBSON]
{}
... The rest is information about removedEvent itself
But if I console log before my for loop I get the following... console.log(removedEvent.invitees);
["luke231#gmail.com","yoda231#gmail.com"]
Here is my code (disregard res headers, I know.):
router.delete(
"/remove/:event_id",
passport.authenticate("jwt", { session: false }),
(req, res) => {
Event.findOneAndRemove({ _id: req.params.event_id }).then(removedEvent => {
console.log(removedEvent.invitees);
for (let i in removedEvent.invitees) {
console.log(removedEvent.invitees[i]);
User.findOne({ email: removedEvent.invitees[i] })
.then(user => {
res.json(user);
})
.catch(err => res.json({ err }));
}
});
}
This is throwing everything off because of me looping through my User.findOne
I didn't figure out why I was getting that output when I console.log'd, but I used forEach() instead of the for loop and it works as expected.
One time two request send this error display and my server close
I have use this code:
exports.getAllCompany = function (req, res) {
Company.find({}, function (err, record) {
if (err) {
res.json({
type: false,
resultData: "Error occured: " + err
});
} else {
res.json({
type: true,
company: record
});
}
});}
The error message:
Error: Can't set headers after they are sent.
at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:356:11)
at ServerResponse.header (/app/node_modules/express/lib/response.js:730:10)
at ServerResponse.send (/app/node_modules/express/lib/response.js:170:12)
at ServerResponse.json (/app/node_modules/express/lib/response.js:256:15)
at /app/server/mobile_api/AdminController/dashboard.js:279:17
at Query.<anonymous> (/app/node_modules/mongoose/lib/model.js:3388:16)
at /app/node_modules/kareem/index.js:259:21
at /app/node_modules/kareem/index.js:127:16
at _combinedTickCallback (internal/process/next_tick.js:73:7)
at process._tickCallback (internal/process/next_tick.js:104:9)
Finally after a long time to solve the issue. follow my answer who have same issue,
exports.getAllCompany = function (req, res) {
res.writeHead(200, {"Content-Type": "application/json"});
Company.find({}, function (err, record) {
if (err) {
res.end(JSON.stringify({
type: false,
resultData: "Error occured: " + err
}));
} else {
res.end(JSON.stringify({
type: true,
company: record
}));
}
});
}
Most probably you are calling res.send() more than once
sharing the /app/server/mobile_api/AdminController/dashboard.js file would be helpful