Search code examples
node.jsmongodbexpressmlab

Make data persist in form using mongodb node express


Hi I can connect to and store to mongodb using mlab but I can't get the data in the form to remain on refresh. The form takes in user input from input-boxes.

Any help would be great.

Thanks


Solution

  • If being able to get the same form data for all the requests (no matter where they are made from)is what you want, then a possible workaround could be as follows:

    1) Store the initial form data(probably empty) in the database, get the ObjectId and hard code it in your code, this way all the updates would be made to that specific MongoDB document only.

    2) The form route (below one) should do nothing except for serving the file which has the form

    app.get('/form1', function (req, res) {
        res.sendFile(__dirname + '/public');
    //record.find({"_id": ObjectId("MLAB ID")})......dont do this
    
    
    });
    

    3) There should be another route that sends form data

    app.get('/getdata', function(req, res) {
            record.find({"_id": ObjectId("MLAB ID")}, function(err, doc) {
                res.send(doc)
            })
        });
    
    

    4)The static file that you send to the client should have a javascript function such that it asks for the form data as soon as your window loads and then sets the value of input elements from that data recieved:

     window.onload = function() {
            //make a GET request to /getdata to get form data....store it in obj
            //then set the input values
           document.getElementById("yourchoice").value = obj.yourchoice;
            //and set the value of other input fields ....in similar amnner
    
        }
    

    5) The POST request you make should update that specific document( findOneAndUpdate?? )

    Disadvantage of this method:

    For one operation we request a file from server and then another request to get form data, so two requests for one operation, since we cannot use both res.sendFile() and res.json() together...one way to get around this is to hide the form data as well in the HTML document using a template engine. More about this can easily be found. Anyways the above method does solve your purpose.

    I hope I correctly understood the problem statement.

    Happy coding!!

    Edit:Although the above mentioned points are explainatory, I have written a sample snippet at : https://pastebin.com/AvgVyx7b

    It works perfectly fine