I have a trouble serializing and parsing arrays. I show you code and after explain:
Code
Client POST request:
jQuery('.upload').on('click', function()
{
var flats = [];
var data_building_id = jQuery(this).attr('data-building-id');
jQuery('#setup-' + data_building_id).find('.flat-value').each(function()
{
flats.push(jQuery(this).html());
});
flats.sort();
var data = 'building={"flats":' + JSON.stringify(flats) + ',"_id":"' + data_building_id + '"}' ;
makeTheRequest('post', 'admin_buildings', data, 'json', onSuccessSignLog, onErrorGenericAJAX);
});
Building Controller Code:
router.post('/admin_buildings', function(req, res)
{
var building = req.body.building;
if(req.session && req.session.user && (req.session.user.rol=="Admin" || req.session.user.rol=="superAdmin") && building)
{
building = JSON.parse(building);
building.flats = new Array(building.flats);
if(building.flats instanceof Array)
console.log("buildings.js-> admin_building-> flats is array");
buildingDB.updateBuilding(building, function(results)
{
//here goes the returning values to the client.
});
}
});
Building Model Code:
this.updateBuilding = function(building, callback)
{
Model.findById(building._id, function(err, doc)
{
if(err) callback({success:0, error:1, result: err});
else if(!doc || doc.lenght==0) callback({success:0, error:1});
else
{
if(building.flats && building.flats instanceof Array)doc.flats = [building.flats];
for (var x=0;x<doc.flats.length;x++)
console.log("The element " + x + " on the array flat doc is: " + doc.flats[x]);
if(building.flat) doc.flats.push(building.flat);
doc.save(function(err)
{
if(err)callback({success:0, error:1, result: err});
else callback({success:1, error:0, result:doc});
});
}
});
}
Ok!! I try to summarize the most that I can, but...
What I do is, on the client side: take some data, put them into array and sort it alphabetically (eg: 1a, 1b, 2a, 2b... flat and door), finally I serialize this array and send on a post.
The controller take the seralized data (array and id of building) and parse them. For this testings I ask if the flat field of the building parsed object is an array, in positivve case the log shows "...flat is array". And then I pass it to the model.
The model only change some fields (address, city, state... not on the code) of the recovery doc if the object (building) passed as argument has them. And, too for testing, the for loop must shows all the flats on the array, and it does... but not one by one and THIS IS THE PROBLEM. It must to show someething like:
The element 0 on the array flat doc is: 1a
The element 0 on the array flat doc is: 1b
The element 0 on the array flat doc is: 2a
The element 0 on the array flat doc is: 2b
But nonotheless, it shows this:
The element 0 on the array flat doc is: 1a,1b,2a,2b
Is possible to do what I want and I am making some bad step?? What I am doing wrong??
Thank you very much.