【问题标题】:Trying to update LokiJS db but getting 'Trying to update unsynced document' error尝试更新 LokiJS db 但出现“尝试更新未同步的文档”错误
【发布时间】:2019-06-27 07:37:45
【问题描述】:

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

【问题讨论】:

    标签: javascript lokijs


    【解决方案1】:

    我偶然发现了这个问题,问题是在调用peopleAndFruits.update 时,您传递的文档需要是集合中的现有项目,这意味着它必须有一个$loki id。在您的情况下,您可以选择

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

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

      • 优秀的答案!
      • 感谢哈迪德:-)
      猜你喜欢
      • 1970-01-01
      • 2018-03-22
      • 2023-04-10
      • 1970-01-01
      • 1970-01-01
      • 2016-02-23
      • 1970-01-01
      • 2015-07-09
      • 1970-01-01
      相关资源
      最近更新 更多