I have a datasource that is only available to me in XML format rather than JSON, the preferred data type for MongoDB. I have a method that allows JSON posting to MongoDB collection and I'm trying to modify it to handle XML data instead.
Here's my modified method:
exports.addXMLTicket = function(req, res) {
var xml2js = require('xml2js');
var xml = req.body;
var parser = new xml2js.Parser();
parser.parseString(xml, function (err, ticket) {
console.log('Done parsing XML');
console.log('Adding ticket: ' + JSON.stringify(ticket));
db.collection('tickets', function(err, collection) {
collection.insert(ticket, {safe:true}, function(err, result) {
if (err) {
res.send({'error':'An error has occurred'});
} else {
console.log('Success: ' + JSON.stringify(result[0]));
res.send(result[0]);
}
});
});
});
}
And here's the XML data:
<?xml version='1.0'?>
<instance dm:form_version='1.0' dm:submit_time='2012-04-02 12:33:26 UTC' dm:submitting_user='Dusan Babich' writeTime='2011-04-26T15:23:11.506' dm:form='A First Form' dm:submitting_device='iPhone_d6e2542effafbcc8d0e6bf0ef2917b76dea4faf8' xmlns:dm='http://mobileforms.devicemagic.com/xforms' xmlns='http://www.devicemagic.com/xforms/demo/2d3698c0-650c-012e-7e8e-12313b079c72'>
<untitled_form_1>
<quality_of_day>{{VALUE}}</quality_of_day>
<inbox_overflow>{{VALUE}}</inbox_overflow>
<next_holiday>{{VALUE}}</next_holiday>
<comments>{{VALUE}}</comments>
</untitled_form_1>
</instance>
And finally my CURL request:
curl -i -X POST -H "Content-Type: text/xml" -d "<?xml version='1.0'?><instance dm:form_version='1.0' dm:submit_time='2012-04-02 12:33:26 UTC' dm:submitting_user='Dusan Babich' writeTime='2011-04-26T15:23:11.506' dm:form='A First Form' dm:submitting_device='iPhone_d6e2542effafbcc8d0e6bf0ef2917b76dea4faf8' xmlns:dm='http://mobileforms.testdomain.com/xforms' xmlns='http://www.testdomain.com/xforms/demo/2d3698c0-650c-012e-7e8e-12313b079c72'><untitled_form_1><quality_of_day>test</quality_of_day><inbox_overflow>test</inbox_overflow><next_holiday>test</next_holiday><comments>test</comments></untitled_form_1>" http://127.0.0.1:3000/ticketsxml
There error I'm getting is, "TypeError: Cannot read property '_id' of undefined" which seems to be happening because it's not getting the body from the POST. However, when I post in JSON format it works just fine.
Any suggestions would be much appreciated, thanks!
Check out the xmlParser middleware: https://github.com/brandid/express-xmlBodyParser