Problem: When creating the first document for a user, query takes too long
I'm creating some report, of the schema Report. I also have a UserSchema. I create a document in my UI and pass that data to a post request which is this:
exports.addSubReport = function(req,res) {
var id = req.body.masterform;
var subform = new Report();
var myDate = Date();
subform.title = req.body.title;
subform.date = req.body.date;
subform.date = myDate;
subform.owner = req.user;
subform.body = req.body.body;
subform.save();
Report.findById(id, function (err, report) {
if(err) {
res.redirect('/404NotFound');
}
else {
report.subreport.push(subform);
subform.parentReport = report;
report.save();
}
});
User.findById(req.body.id, function (err, user) {
user.forms_created.push(subform);
subform.owner = req.user;
subform.authors[0] = user.profile.firstName + " " + user.profile.lastName;
subform.author = user;
subform.save();
});
res.json(req.body);
};
this works fine and creates the object the way I want it to, however after creating the document, I set the state in my UI to 'Wait' until I can recieve the JSON with this new Report I just created. This is the GET request code:
exports.allMyReports = function(req, res) {
var id = req.user._id;
var totalproc = 0;
var dupe = [];
Report.find({"author" : id}, function (err, form) {
dupe = form;
dupe.forEach(function (person) {
User.findById(person.author, function (err, user) {
if (!err) {
person.authors[0] = user.profile.firstName + " " + user.profile.lastName;
person.save();
totalproc = totalproc + 1;
}
if (totalproc == dupe.length) {
res.json(dupe);
}
}
);
});
});
};
However the problem is that on every first report I create for a user, it takes an extremely long time. It's most likely the query of searching for it by author but than I thought well.... if the user has 15 documents already how does it even find all those documents instaneously? I have no idea why it takes so long in this case though and I haven't been able to come up with a solution yet but I think it has to do with how I'm querying.
Here is a sample of how i do it in the UI:
_onCreateReport = () => {
const title = React.findDOMNode(this.refs.title).value;
const date = React.findDOMNode(this.refs.date).value;
const body = React.findDOMNode(this.refs.body).value;
ReportsActions.addNewReport({
title: title,
date: date,
body: body
});
ReportsActions.getMyReports();
}
I perform the action of adding a new report ('post' request to API), and then getMyReport 'get' request to api for all reports belonging to me, once that returns it shows a new render of 3 buttons, one to view that document, one to view all my documents, one to create another report.
All I did, was request all the documents, and figure it out in the front-end. It reduced the time of the ajax call and I just filtered it out in my front-end which performs quick and doesn't hold the server up.