Express res.render stuck in infinite loop - javascript

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.

Related

Express routing to search results

Got a real newbie question here. So i'm building an events page in which I'd like to filter results by date input (standard html form). I've made this a get request with the following routing:
app.get("/eventByDate/:date", async (req, res) => {
const d = req.params.date;
const data = await Event.find({ date: d });
if (data) {
res.render(`./events/eventByDate`, { data });
} else {
console.log("THERE IS NO DATA");
}
});
EventByDate is its own page, and I can access the relevant stuff by manually typing, for example, http://localhost:3000/eventByDate/2021-01-20
But as it is just now, the form submit takes me there but with the query string in the title, i.e. http://localhost:3000/eventByDate/?date=2021-01-20
Does anyone have a solution to this? My initial idea was to try to remove the query string but this seems a little inelegant, so I'm sure there is a simpler way that I'm completely missing?
Thanks in advance.

How to fix deleteOne() function of a mongoose model when it does not delete by req.params.id?

Firstly to be mentioned, I'm absolutely new to Node.Js and MongoDB.
I'm coding a back end API with Node.Js and MongoDB which will deal with GET, POST, DELETE requests from the front end, quite simple stuff.
I'm stuck while working with DELETE functionality.
Here is my posts.service.ts file contains this deletePost() function which sends the postId to the back end app.js file.
`
deletePost(postId: string) {
this.http.delete('http://localhost:3000/api/posts/' + postId)
.subscribe(() => {
console.log(postId);
console.log('Deleted');
});
}
`
I have added this console.log(postId) to check whether it is actually containing the actual postId and found that it does. I have also matched it with the real Id in MongoDB by checking through mongo shell.
Here is the delete() function in the back end app.js file that should do the actual task.
`
app.delete("/api/posts/:id", (req, res, next) => {
Post.deleteOne({ _id: req.params.id }).then(result => {
console.log(result);
res.status(200).json({message: "Post deleted"});
});
});
`
The console.log(result) line should print some result in the terminal, but it does not, so does not it delete the collection in the DB.
I`m running this on an Ubuntu 16.04 LTS pc.
Some clue would mean great help. Thank you very much for your kind effort.
deleteOne doesn't return the deleted document. It always deletes the first matching document and return the number of documents deleted with the boolean value.
From the mongodb docs deleteOne:
Returns:
A document containing: A boolean acknowledged as true if the operation ran with write concern or false if write concern was
disabled
deletedCount containing the number of deleted documents
From the mongoose docs
Deletes the first document that matches conditions from the
collection. Behaves like remove(), but deletes at most one document
regardless of the single option.
I was facing exactly the same, i solved returning the deleteOne promise object and then using the .then property of the promise.
Something like this:
Model.js
...
bicicleSchema.statics.deleteById= function(id, cb){
return this.deleteOne({code: id}, cb);
};
...
module.exports = mongoose.model('Bicicle', bicicleSchema);
Service.js
var Bicicle = require('../../../model/bicicle');
...
const id = req.params.id;
Bicicle.deleteById(id).then(()=>{
//your code
});
...

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

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.

Error with get request for users

When using a get request for all the users in my database (see code below) i only get the "first" user in the database. If i instead try to use the "findOne"-method i get the same user as before no matter what i put in (the username doesn't even have to be in the db it still gives me the same user). I've been trying to understand why this isn't working but can't find any problems with the code. Could it be a problem with db settings or something similar? All help is appreciated!
In AuthController:
// Get all users
AuthController.allusers = function(req, res) {
User.find({}, function(err, users) {
}).then(function(users) {
res.json({users: users});
});
}
In routes:
// GET Routes.
router.get('/users', AuthController.allusers);
Since you are using Sequelizejs, you might want to do findAll.
AuthController.allusers = function(req, res) {
User.findAll().then(function (users) {
res.send({users: users});
}
}
According to the docs:
find - Search for one specific element in the database
findAll - Search for multiple elements in the database

Node.js event loop blocked from express routes

I have an express app and one of the functionalities is "moving" files. For example, you can drag a folder to another folder and have it's contents move. Once all the contents are moved, the server responds accordingly.
What I've found is that when doing this with folders that contain many files (possibly additional folders), this can cause the event loop to get blocked for up to 3+ seconds, which I've found using blocked.
Would anyone have any suggestions on how I could prevent this? One option I though is to use child_process.fork, I'm not sure how that will tie into an http route, but I'll test it. Would there be any other ways to improve something like this?
Code example: This is one part I'm testing now, that basically is building a "tree" from a materialized path pattern in Mongo:
var items = []
Items.find({parentId: null, user_id: '123', type: 'directory'})
.exec(function(err, docs) {
if (err) return res.send(err);
async.each(docs, function(doc, cb) {
doc.getArrayTree({
condition: {type: 'directory'}
}, function(err, childDocs) {
if (_.isEmpty(childDocs)) return cb();
items.push(childDocs[0]);
cb();
});
}, function(err) {
if (err) return res.send(err);
res.send(items);
});
});
This is using mongoose materialized, specifically I believe the issue/delay is with this. Which is being called for every item returned. There must be a more efficient way, perhaps with an aggregate. This is showing about a +-500ms delay, of course this degrades as there are more documents.

Categories