javascriptnode.jsleveldb

Not able to write data into a leveldb file using batch


I just started to learn level.db using the level module in node.js

var level = require('level')
var db = level('batch.db', { valueEncoding: 'json' })
var batch = [] 
  for (var i = 0; i < 10; i++) {
 batch.push({ key: 'n' + i, value: i*1000 }) 
}
 db.batch(batch, function (err) {
 if (err) console.error(err)
})

But this code gives me the following ERROR

Error [WriteError]: type must be 'put' or 'del' at C:\Users\mathe\Desktop\levelDB-and-Crypto\node_modules\level-packager\node_modules\levelup\lib\levelup.js:274:23

Can someone let me know whats wrong?


Solution

  • From the GitHub page of leveldb here, we can see an example :

    const ops = [
      { type: 'del', key: 'father' },
      { type: 'put', key: 'name', value: 'Yuri Irsenovich Kim' },
      { type: 'put', key: 'dob', value: '16 February 1941' },
      { type: 'put', key: 'spouse', value: 'Kim Young-sook' },
      { type: 'put', key: 'occupation', value: 'Clown' }
    ]
    
    db.batch(ops, function (err) {
      if (err) return console.log('Ooops!', err)
      console.log('Great success dear leader!')
    })
    

    Each item in the array has the property "type", which can be "del" or "put".

    So, I think the code should be :

    var level = require('level')
    var db = level('batch.db', { valueEncoding: 'json' })
    var batch = [] 
    for (var i = 0; i < 10; i++) {
     batch.push({ type : "put", key: 'n' + i, value: i*1000 }) 
    }
    db.batch(batch, function (err) {
     if (err) console.error(err)
    })