0

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

是 parse.com 的 npm 模块,但没有类似的方法

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

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

4

1 回答 1

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!);
  };
});
于 2013-08-13T14:06:51.450 回答