Search code examples
node.jsnedb

Nedb Find one item and change another


I am finding a piece of data by searching for the name, however, that person also has a score count, how could I just get the score count.

database.find({ username: username }, function(err, doc) {
    const data = doc
    console.log(data)

    if(data.length < 1 || data == undefined) {

    const scorecount = 1;
    database.insert({ username, scorecount})

    } else {
        console.log(data)
        //Here is where I want to be able to just get the score count and be able to change it
    }
})

Thanks for any help


Solution

  • I've never used NeDB; but in general what you need to do is map between the element you receive in doc and the argument that database.insert() expects. From reading the documentation I think you can just modify doc and pass it right back in:

    data.forEach((row) => {
      row.scorecount = (row.scorecount || 0) + 1
      database.insert(row)
    })
    
    

    Side note: if (data.length < 1 || data == undefined). If data is in fact undefined then data.length will throw an error. Check data == undefined first. Or better yet, !data will catch any value which is falsy.