Node.js user keeps overwriting user despite different names

I made a function to put user with some data in a json file but it overwrites each user when they add their data in.
on message “write” it adds their username to database with some values.

client.on('message', message => {
  if(message.content.toLowerCase() === 'write') {
    async function readandwrite() {
      getData = require('./PlayerArea.json');     //grabs and parses data
      message.channel.send('Getting data...');
      await new Promise((resolve, reject) => setTimeout(resolve, 3000));
      player = message.author.username;           //sets username to player
      if(getData.data [player] === undefined) {   //if nothing is there define
        getData.data = {[player]: {Var: 1, Var1: 1}}
        stringdata = JSON.stringify(getData);     //put the data into string (Could be what is overwriting each user)
        message.channel.send('Putting data into string...');
        await new Promise((resolve, reject) => setTimeout(resolve, 3000));
        message.channel.send('Writing data to file...');
        fs.writeFileSync('./PlayerArea.json', stringdata, {encoding: 'utf8', flag: 'w'}); //writes file with flag of write
        await new Promise((resolve, reject) => setTimeout(resolve, 3000));
        message.channel.send('Data has be written in file!');

      }
    }
    readandwrite();
  }
})

The key issue I think are these lines:

getData.data = {[player]: {Var: 1, Var1: 1}}

your re-assigning getData.data with the player information, thus overwriting whatever was there before.

To “update” the “data” property on getData object before writing it back to the json file, you can do something like this:

getData.data = {...getData.data, [player]: {Var: 1, Var1: 1}};

This uses object destructuring to essentially make a shallow copy, then you add your variables to it. If there already is a property that matches with the player, you will overwrite it though.

(an alternate approach is using object.assign, but its more to type);

This should essentially “upsert” your data, where you either create it if it doesn’t exist, or update what is already there.

Hope that helps, good luck!