Kind of a sequel to this question, I need to accept multiple objects in a POST request and then for each object process it, save it, and then return the saved object to the frontend (so that the client can see which columns were successfully edited).
When I use .map, it does save to the database and I can confirm this. However, I have two problems:
- It does not execute
res.locals.retval.addData(dtoObject);
correctly, and my returning payload has no data transfer objects inside of it. My object validation cannot be done inside of the callback of
map
. I initially triedreduce
, but that didn't work at all and just saved all the same values to each database object. How can I exclude invalid JSON objects while I'm mapping them?var jsonObjects = req.body; //for (var n in req.body) { var promises = jsonObjects.map((jsonObject) => { var transform = new Transform(); // VALIDATION OF jsonObject VARIABLE IS HERE if (jsonObject.id == 0) { var databaseObject = Database.getInstance().getModel(objectName).build(jsonObject); transform.setNew(true); transform.setJsonObject(jsonObject); transform.setDatabaseObject(databaseObject); transform.baseExtract() .then(() => transform.extract()) .then(() => transform.clean()) .then(() => transform.getDatabaseObject().save()) .then(function(data) { // PROCESSING DATA }).catch((e) => { // ERROR }); } else { var queryParameters = { where: {id: jsonObject.id} }; console.log("Query parameters: "); console.log(queryParameters); Database.getInstance().getModel(objectName).findOne(queryParameters).then((databaseObject) => { transform.setJsonObject(jsonObject); transform.setDatabaseObject(databaseObject); }) .then(() => transform.baseExtract()) .then(() => transform.extract()) .then(() => transform.clean()) .then(() => transform.getDatabaseObject().save()) .then((data) => { // PROCESSING DATA }).catch((e) => { // ERROR }); } }); Promise.all(promises) .then((results) => { return next(); }).catch((e) => { throw e; });
Here's the resulting payload:
{
"errors": [],
"warnings": [],
"data": []
}