Level / level

Universal abstract-level database for Node.js and browsers.
MIT License
1.55k stars 106 forks source link

Question: Fetch all values #201

Closed ostjen closed 3 years ago

ostjen commented 3 years ago

Is there a way to fetch all values without creating a stream?

context: I'm writing a method that returns the last N entries in the database.

vweevers commented 3 years ago

Duplicate of https://github.com/Level/levelup/issues/491. Short answer: you can use an iterator instead of a stream, but there's no dedicated simple API for fetching multiple values.

ostjen commented 3 years ago

@vweevers is there any example of the correct usage of the iterator? I can only access the last value, when I try to actually iterate over it all values end up being undefined

vweevers commented 3 years ago

Roughly:

function collectLast (limit, callback) {
  const iterator = db.iterator({ reverse: true, limit })

  const end = function (err) {
    iterator.end(function (err2) {
      callback(err || err2)
    })
  }

  const loop = function () {
    iterator.next((err, key, value) => {
      if (err) return end(err)

      if (key === undefined && value === undefined) {
        // reached the end
        return end()
      }

      // do something with key & value
      // ..

      loop()
    })
  }

  loop()
}
ostjen commented 3 years ago

Thanks, it worked! :smile:

vweevers commented 3 years ago

Oh I forgot about https://github.com/Level/concat-iterator :)