如何将一组对象添加到parse.com db?

时间:2013-08-13 12:27:07

标签: node.js parse-platform

我正在开发一个应用程序,需要一次添加很多项目 我怎么能用node.js做到这一点?

This是parse.com的npm模块,但没有像

这样的方法
insertAll("Foo", [objs...], ...)

我不想每次都插入单个对象。

1 个答案:

答案 0 :(得分:1)

编写一个便利函数,在您的应用程序和parse.com之间进行接口。您必须编写一次迭代代码(或调试我的)

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!);
  };
});