shift66
shift66

Reputation: 11958

How to add an array of objects to parse.com db?

I'm developing an application and need to add many items at a time.
How can I do that with node.js?

This is the npm module for parse.com but there is no method like

insertAll("Foo", [objs...], ...)

I don't want to insert single object every time.

Upvotes: 0

Views: 601

Answers (1)

Plato
Plato

Reputation: 11052

Write a convenience function that interfaces between your application and parse.com. You will have to write the iteration code once (or debug mine)

var async = require('async');
var parseApp = require('node-parse-api').Parse;
var APP_ID = "";
var MASTER_KEY = "";
var parseApp = new Parse(APP_ID, MASTER_KEY);

function insertAll(class, objs, callback){
  // create an iterator function(obj,done) that will insert the object
  // with an appropriate group and call done() upon completion.

  var insertOne = 
  ( function(class){
      return function(obj, done){
        parseApp.insert(class, obj, function (err, response) {
          if(err){  return done(err);  }
          // maybe do other stuff here before calling done?
          var res = JSON.parse(response);
          if(!res.objectId){  return done('No object id')  };
          done(null, res.objectId);
        });
      };
    } )(class);

  // async.map calls insertOne with each obj in objs. the callback is executed
  // once every iterator function has called back `done(null,data)` or any one
  // has called back `done(err)`. use async.mapLimit if throttling is needed

  async.map(objs, insertOne, function(err, mapOutput){
    // complete
    if(err){ return callback(err) };
    // no errors
    var objectIds = mapOutput;
    callback(null, objectIds);
  });
};

// Once you've written this and made the function accessible to your other code,
// you only need this outer interface.

insertAll('Foo', [{a:'b'}, {a:'d'}], function(err, ids){
  if(err){ 
    console.log('Error inserting all the Foos');
    console.log(err);
  } else {
    console.log('Success!);
  };
});

Upvotes: 1

Related Questions