0

I am having problems trying to connect variables from a browser based game to store in my mongoDB database.
Basically this is a condensed example as there will be numerous additional variables I will track and save, but in the example below I want the "round" to increment on button click. On the button click, I want the round number to be saved to a mongoDB database.

index.ejs file:

<h1>Round <span id="round">1</span></h1>
    <form action="/" method="POST">
        <button id="endbutton" type="submit">End Turn</button>
    </form>
    <script src="../scripts/game.js"></script>

game.js file:

let round = 1;
 
 function endTurn(){
    round += 1;
    document.querySelector("#round").innerHTML = round;
}

let endTurnButton = document.querySelector("#endbutton");

endTurnButton.addEventListener("Click", endTurn);
    
module.exports = {round, endTurn};

app.js file:

const express = require("express");
const app = express();
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const path = require('path');
const gameJS = require('./scripts/game');

mongoose.connect("mongodb://localhost/variableTest", {useNewUrlParser: true, useUnifiedTopology: true, useFindAndModify: false})
.then(() => {
    console.log("Mongo connection open");
})
.catch(err => {
    console.log("Mongo connection error occurred:")
    console.log(err)
})

app.use(express.static(__dirname + "/public")); 


app.use(bodyParser.urlencoded({extended: true})); 
app.set('views', path.join(__dirname, 'views'));
app.set("view engine", "ejs");

const { Schema } = mongoose;

const gameSchema = new Schema({
   date: Date,
   round: Number,
  });

const Game = mongoose.model("Game", gameSchema);

//=================
//ROUTES
//=================

app.get("/", async(req, res) =>{
    res.render("index");
});


app.post('/', async(req, res) => {
    const game = new Game({
        date: Date.now(),
        round: gameJS.round,
    });
    await game.save();
    
})




//=================
//SERVER
//=================

app.listen(3000, () => {
    console.log("VariableTest server has started.");
})
Soonerdev
  • 48
  • 5
  • document is not supported in node.js check [here](https://stackoverflow.com/questions/32126003/node-js-document-is-not-defined) – Apoorva Chikara Mar 12 '21 at 17:38
  • Though the document error is a current issue, the main problem I am trying to solve is how to get variables from the game.js file and save them to mongoDB when the button is clicked/'form' submitted. – Soonerdev Mar 12 '21 at 17:52
  • Does this approach [help](https://stackoverflow.com/questions/53390893/how-to-pass-variable-from-one-ejs-to-another-ejs-in-node-js) you? – Apoorva Chikara Mar 12 '21 at 18:30

0 Answers0