RL1234
RL1234

Reputation: 11

Trying to update LokiJS db but getting 'Trying to update unsynced document' error

Trying to dynamically add entries of people and fruit that they own in Loki JS but I keep getting the Trying to update unsynced document. Please save the document first by using insert() or addMany() error. Anyone have any ideas of how to do this successfully?

I've logged the values coming in and they match what is found in the db already.

const loki = require('lokijs');

const db = new loki('loki.json');

const peopleAndFruits = db.addCollection('peopleAndFruits');

peopleAndFruits.insert({ dbname: 'person', fruits: 10 });

const createOrInsertUserToDb = (name, fruitNumber) => {
    const data = peopleAndFruits.find({ dbname: name });
    console.log('db entry before updated ', data[0].dbname);
    if (data[0].dbname !== name) {
        // console.log('this person did not exist in our database');
        peopleAndFruits.insert({ dbname: name, fruits: fruitNumber });
    } else {
        // console.log('previously existing entry');
        peopleAndFruits.update({
            dbname: data[0].dbname,
            fruits: Number(fruitNumber + data.fruits),
        });
    }
    // console.log('data after update or insert', peopleAndFruits.data);
    db.saveDatabase();
};

Upvotes: 1

Views: 2136

Answers (2)

Cao Shouguang
Cao Shouguang

Reputation: 148

You will need to select the doc first from the collection preferably by its unique id:

const loki = require('lokijs');

const db = new loki('loki.json');

const peopleAndFruits = db.addCollection('peopleAndFruits', {unique: '_id'});

peopleAndFruits.insert({_id:"spy_007", dbname: 'person', fruits: 10 });

let doc = peopleAndFruits.by("_id", 'spy_007') //select the doc first to be updated

doc.dbname = "John"  //update its values
doc.fruits = 100   //update its values

peopleAndFruits.update(doc) //update the collection

Upvotes: 3

Jan Hangebrauck
Jan Hangebrauck

Reputation: 41

I stumbled upon this question, the problem is that when calling peopleAndFruits.update, the doc you pass needs to be an existing item in the collection, that means it has to have a $loki id. In your case, you could either go with

peopleAndFruits.update({
  ...data[0],
  fruits: +fruitNumber + fruits;
});

or

peopleAndFruits.findAndUpdate({$loki: data[0].$loki}, item => {
  item.fruits = +fruitNumber + fruits;
});

Upvotes: 3

Related Questions