Error when trying to store an array in ScriptDb

前端 未结 2 472
你的背包
你的背包 2021-01-16 01:51

I have an array of objects that is created by my script and I am trying to copy that array into a new array and then store it in scriptDb using the following function:

相关标签:
2条回答
  • 2021-01-16 02:28

    ScriptDb only stores map objects. You could however store a map that contains an array!

    You can use arrays to save several objects in a single call using db.saveBatch.

    0 讨论(0)
  • 2021-01-16 02:42

    As @Thomas said, you can save an array in a map object.

    You don't need to perform a copy operation before putting an object into the ScriptDB, either. You could save your array by simply db.save({myArray}), and remember the ID.

    Here's some minimalist code to demonstrate. I'm showing two ways to retrieve your saved array - one by ID, which seems to be the way you were planning to, but also a second way using a "key" value for a query. If you expect to retrieve the contents of ScriptDB in a later run of your code, this approach eliminates the need to somehow remember the ID of the stored array.

    function saveArray (currentArray) {
      var db = ScriptDb.getMyDb();
      return db.save({type: "savedArray", data:currentArray}).getId();
    }
    
    function loadArrayById (id) {
      var db = ScriptDb.getMyDb();
      return db.load(id).data;
    }
    
    function loadArrayByType () {
      var db = ScriptDb.getMyDb();
      var result = db.query({type: "savedArray"});
      if (result.hasNext()) {
        return result.next().data;
      }
      else {
        return [];
      }
    }
    
    function test() {
      var arr = ['this','is','a','test'];
      var savedId = saveArray( arr );
      var loaded1 = loadArrayById( savedId );
      var loaded2 = loadArrayByType();
      debugger;  // pause if running debugger
    }
    

    Here's what you'll see at the debugger pause:

    Screenshot of debugger

    Note that by using the map tag data to pull the array from the saved object, both loaded1 and loaded2 are identical to the source array arr.

    0 讨论(0)
提交回复
热议问题