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.");
})