试图动态添加他们在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();
};
最佳答案
我偶然发现了这个问题,问题是调用peopleAndFruits.update
时,您传递的doc必须是集合中的现有项,这意味着它必须具有$loki
id。就您而言,您可以选择
peopleAndFruits.update({
...data[0],
fruits: +fruitNumber + fruits;
});
要么
peopleAndFruits.findAndUpdate({$loki: data[0].$loki}, item => {
item.fruits = +fruitNumber + fruits;
});