techfort / LokiJS

javascript embeddable / in-memory database
http:/techfort.github.io/LokiJS
MIT License
6.76k stars 482 forks source link

clone is required to use pre-update #933

Closed retorquere closed 1 year ago

retorquere commented 1 year ago

See this test script. The controldb fork does run pre-update before the DB is updated.

const engine = require('lokijs')
const key = '$loki'
// const engine = require('controldb')
// const key = '$ctrl'

function assert(cond, msg) {
  if (!cond) throw new Error(msg)
}

const items = [
  { id: 0, firstname: 'George' },
  { id: 1, firstname: 'Lenny' },
]

const DB = new engine('db', { clone: true })
const coll = DB.addCollection('names', {
  indices: [ 'id', 'firstname' ],
  unique: [ 'id' ],
})
coll.insert(items)

coll.on('pre-update', item => {
  const old = coll.get(item[key])
  assert(old.firstname == 'George', `old = ${old.firstname}`)
  assert(item.firstname == 'Mark', `item = ${item.firstname}`)
})
coll.on('update', item => {
  console.log('update', item)
})
coll.on('delete', item => {
  console.log('delete', item)
})

const obj = coll.findOne({ id: 0 })
console.log('found', obj)
obj.firstname = 'Mark'
coll.update(obj)
console.log(coll.findOne({ id: 0 }))
coll.remove(obj)
console.log(coll.findOne({ id: 0 }))
retorquere commented 1 year ago

Never mind, clone needs to be set on the collection.