尝试更新LokiJS数据库,但出现“尝试更新未同步的文档”错误

时间:2019-06-27 07:37:45

标签: javascript lokijs

试图动态添加Loki JS中他们所拥有的人和水果的条目,但我不断遇到Trying to update unsynced document. Please save the document first by using insert() or addMany()错误。任何人都对如何成功执行此操作有任何想法?

我已经记录了进来的值,它们与数据库中已经找到的值匹配。

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();
};

2 个答案:

答案 0 :(得分:1)

我偶然发现了这个问题,问题是调用peopleAndFruits.update时,您传递的doc必须是集合中的现有项,这意味着它必须具有$loki的id。就您而言,您可以选择

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

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

答案 1 :(得分:0)

您需要首先从集合中选择文档,最好通过其唯一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