I'm building a web application to track scores for a game, but I have run into an issue when trying to save the score entries to the db. I'm using Node JS and NeDB. The client requests the post API and database.insert(data) does not save to PlayerResults.db every time. It does once, maybe twice if I'm lucky and then nothing again. There are no errors thrown and the response is showing the data to the client correctly. Is there something I'm missing? A limitation with the insert function or NeDB?
const { request, response, json} = require('express');
const express = require('express');
const Datastore = require('nedb');
const app = express();
app.listen(3000, () => console.log('listening for submissions'));
app.use(express.static(__dirname))
app.use(express.json())
const database = new Datastore('PlayerResults.db')
database.loadDatabase();
app.post('/api', (request, response) => {
console.log("Score Submitted")
const data = request.body;
const timestamp = Date.now()
for(i=0; i<data.length; i++){
data[i].timestamp = timestamp
}
database.insert(data)
response.json({
status: 'success',
timestamp: timestamp,
return: data
});
})
Here is the function calling the API:
async function submit(matchdata){
console.log(matchdata)
const options = {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(matchdata)
}
const response = await fetch('/api', options);
const data2 = await response.json()
console.log(data2)
I've tried a different datastore, loading the db within the API and then inserting, inserting one entry at a time within the for loop, to no avail.
What was happening was I was creating
matchdatabased off what was pulled from a different db. NeDB adds a_idfield to all db entries. When using insert for the same player again it was not adding a new entry because of the_idfield as it already existed in the db.To resolve I now strip the
_idfield from the objects inmatchdatabefore posting to the server and they insert fine.