Home > Back-end >  Javascript API is not inserting to NeDB, but it is returning the data to the client without error
Javascript API is not inserting to NeDB, but it is returning the data to the client without error

Time:11-22

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.

CodePudding user response:

What was happening was I was creating matchdata based off what was pulled from a different db. NeDB adds a _id field to all db entries. When using insert for the same player again it was not adding a new entry because of the _id field as it already existed in the db.

To resolve I now strip the _id field from the objects in matchdata before posting to the server and they insert fine.

async function submit(matchdata){
  console.log(matchdata)

  for( i = 0; i < matchdata.length; i  ){
    delete matchdata[i]._id
  }

  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)
}
  • Related