Express.JS + MongoDB is calling route repeatedly with seemingly random values - javascript

I am trying to code a receipt route that grabs receipts by their ID and then renders them to the page.
My route with MongoDB:
app.get('/receipt/:transactionId', (req,res) => {
var transactionId = req.params.transactionId;
console.log('TRANSACTION ID: ' + transactionId);
SquareTransactionDB.findOne({_id: transactionId})
.then((transaction) => {
console.log('FOUND A TRANSACTION');
res.render('receipt.hbs', {
chargeList: transaction.receipt_list,
date: transaction.created_on,
transactionId
});
return;
}).catch((e) => {
console.log(e);
})
});
What I get as a result is an infinitely waiting web-page, and these errors being thrown in Node terminal:
As soon as I Ctrl+C cancel the server, the page renders. Otherwise, the page just waits for a response.
How is it possible that my code is being called with 'bootstrap.css', or any other value for that matter? What can I do to fix this? I'm on hour 4 and have come to the conclusion that I cannot answer this alone.
I can resolve the page load - with the error still occurring server-side - if I add next() within the catch(e) block.
I appreciate any feedback.
Michael
UPDATE: By adding path '/bootstrap.css' instead of 'bootstrap.css' into my handlebars file, this error stopped getting thrown. Still does not answer my question as to why my style sheet was being used as an argument in parameters - seemingly without purpose.

Related

Firestore transaction fails on get and set of a document which once existed

Given a simple transaction which calls get and then set for the same document reference in a transaction to a db where the document does not exist.
This is the code:
var db = firebase.firestore();
var docRef = db.collection("devtest").doc("doc-1");
return db.runTransaction((transaction) => {
return transaction.get(docRef).then((doc) => {
transaction.set(docRef, {
aValue: "hello world" }); }); });
Running this code in the browser against the emulator database works fine. Running again works again.
But when I (manually) delete the document from the database and then run the code again, it fails with:
FirebaseError: the stored version (1619370082687231) does not match the required base version (0)
at new zr (http://localhost:50001/__/firebase/8.2.3/firebase-firestore.js:1:47931)
Reloading the browser page does not fix this issue. But restarting the emulator does - until the document gets deleted again.
Why is this?
This seams like a bug. There should be no difference in behavior, between a "document never existed" and "document existed and was deleted".
The transaction will only succeed if there is a document to get. If you want to update the document if it exists and set it if it doesn't, try using the catch block to set the document, if it doesn't already exist. You may also want to add some error handling in here, just in case the error isn't related to a document which doesn't yet exist
var db = firebase.firestore();
var docRef = db.doc("devtest/doc-1");
return db.runTransaction((transaction) => {
return transaction.get(docRef)
.then((doc) => {
transaction.set(docRef, {aValue: "hello world"});
})
.catch((err) => {
transaction.set(docRef, {aValue: "hello world"});
});
});

Required JSON file has old values from before running the program

I am writing a discord bot using javascript (discord.js).
I use json files to store my data and of course always need the latest data.
I do the following steps:
I start the bot
I run a function that requires the config.json file every time a message is sent
I increase the xp a user gets from the message he sent
I update the users xp in the config.json
I log the data
So now after logging the first time (aka sending the first message) I get the data that was in the json file before I started the bot (makes sense). But after sending the second message, I expect the xp value to be higher than before, because the data should have been updated, the file new loaded and the data logged again.
(Yes I do update the file every time. When I look in the file by myself, the data is always up to date)
So is there any reason the file is not updated after requiring it the second time? Does require not reload the file?
Here is my code:
function loadJson() {
var jsonData = require("./config.json")
//here I navigate through my json file and end up getting to the ... That won't be needed I guess :)
return jsonData
}
//edits the xp of a user
function changeUserXP(receivedMessage) {
let xpPerMessage = getJsonData(receivedMessage)["levelSystemInfo"].xpPerMessage
jsonReader('./config.json', (err, data) => {
if (err) {
console.log('Error reading file:',err)
return
}
//increase the users xp
data.guilds[receivedMessage.guild.id].members[receivedMessage.author.id].xp += Number(xpPerMessage)
data.guilds[receivedMessage.guild.id].members[receivedMessage.author.id].stats.messagesSent += 1
fs.writeFile('./test_config.json', JSON.stringify(data, null, 4), (err) => {
if (err) console.log('Error writing file:', err)
})
})
}
client.on("message", (receivedMessage) => {
changeUserXP(receivedMessage)
console.log(loadJson(receivedMessage))
});
I hope the code helps :)
If my question was not precise enough or if you have further questions, feel free to comment
Thank you for your help <3
This is because require() reads the file only once and caches it. In order to read the same file again, you should first delete its key (the key is the path to the file) from require.cache

firebase.firestore() .set() not firing first time

I'm not a dev, I'm just learning for my own interest as a hobby.
For my own learning I'm building real world project rather than just following the usual online tutorials.
I'm building a simple vue.js app with vuex and using firebase for auth and db.
I have a method that should just take a value and .set() a new document in a collection with a single piece of data:
HTML
<template>
<div>
<v-btn #click="testing('1', '2')">Testing</v-btn>
</div>
</template>
SCRIPT
methods: {
testing(id, val) {
console.log('entered testing:', id, val)
firebase.firestore().collection('users').doc(id)
.set({
key: val
})
.then(result => {
console.log('created in firestore', result)
})
.catch(error => {
console.error('failed to create in firestore', error)
})
}
...
The problem is that after refreshing the browser the first time I click the button the method runs.
I see the console log 'entered testing' with the correct id and val but the firestore call doesn't appear to run.
Nothing in the console and no network requests.
The second time I click it I see the .then() console log 'created in firestore: undefined' and what looks like 3 network requests, and the doc and data is set correctly!
Every time I click the button after that I see the correct console log, a single network request and the doc and data is set correctly.
Other info...
I have security rules set up on the db but only basic allow if auth != null
The user is logged in when I try this.
I'm not ruling out that there might be something somewhere else in my app which is causing this but there's nothing obvious and I've stripped things right back to debug this. I'm trying to set it up so all firebase requests are done in the store only, with each component just passing it the values it needs, but to debug this I've moved all the logic (including importing firestore) into a single component.
What is going on?
Is there something obvious I'm missing?

I'm getting a 422 error for a function that works

I'm building a bucket-list application, and I've included a function to allow users to delete items/documents from their bucket list/the database. When the function is called, I receive an HTTP 422 Unprocessable Entity error, leading me to believe the function does not work. However, when I refresh the page, the data has been successfully deleted from the database.
Here is the function for deleting the item on the list (the document from the database):
handleDelete = id => {
API.deleteItemFromList(this.props.match.params.id)
.then(res => console.log(res.data))
.catch(err => console.log(err));
};
And here is the code for the api:
deleteItemFromList: function(id) {
return axios.delete("/api/bucketList/" + id);
}
};
So basically, the function does work, but it doesn't work, and I don't understand why. And I'd like to be able to delete the item from the list without getting any error at all.
I'm pretty sure I've supplied all the necessary code, but if I've left something out, or if there's something else you need or would like to see, let me know.
Many thanks in advance!
The error you're getting is TypeError: req.json is not a function. You'll need to change req.json to res.json.
It's the small stuff that'll get ya.

Express res.render stuck in infinite loop

Steps:
pull data from mongodb to populate a link on search page. Be able to click the link to take end user to the generic business page which is auto filled by mongodb. render the page with the JSON data from mongodb.
Issues:
res.render gets stuck in Infinite Loop (no error is thrown also)
I've tried adding an if statement so res.render would not render again, yet still stuck in a loop.
routes/business.js
router.get('/:business', (req, res) => {
console.log(req.params.business);
Business.getBusinessByUrl(req.params.business, (err, business) => {
if (err) throw err;
res.render('business', {
found: true,
business_name: business.business_name,
business_profile_image: business.business_profile_image,
business_url: business.business_url
});
});
});
module.exports = router;
models/business.js
module.exports.getBusinessByUrl = function (businessUrl, callback) {
const query = { business_url: businessUrl };
Business.find(query, callback);
};
Here is what it looks like in the browser :
Imgur
Let me know if you need any other code.
After a while of searching I couldn't find anything helpful. Eventually I figured it out. It happened to be that when I had commented out the line <div w3-include-html="file-included.html"> it stopped infinitely loading. A thank you too everyone who tried to help me.

Categories