试图动态添加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();
};
答案 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