node.js - post array of objects into sails controller -
what controller need create record each object in passed array? create loop?
here's have:
agent.findonebyid(req.query[0].agentid, function(err, agent) { console.log(agent); (i = 0; < req.query.length; i++) { record.findorcreate({userdn: req.query[i].userdn}, { name: req.query[i].name, owner: agent.id }).exec(function (err, newrecord) { if (err) return res.negotiate(err) res.json(newrecord); }) } this create 1 object, there 15 items in array.
here's 1 object array per request:
query: { '0': { userdn: '99999', name: 'test user', agentid: '4' },
use built-in bluebird library. specifically, promise.all().
code example (also using lodash foreach simplify things):
var promise = require('bluebird'); ... agent.findonebyid(req.query[0].agentid, function(err, agent) { console.log(agent); var promises = []; _.foreach(req.query, function(record) { promises.push(record.findorcreate({userdn: record.userdn}, { name: record.name, owner: agent.id })); }); promise.all(promises) .then(function(records) { res.json(records); }) .catch(function(err) { return res.negotiate(err); }) }
Comments
Post a Comment