I have the following JSON data to insert into my MongoDB:
[ { type: 'date',
label: 'Date Field',
className: 'form-control',
name: 'date-1500532692937' },
{ type: 'date',
label: 'Date Field',
className: 'form-control',
name: 'date-1500532693129' },
{ type: 'checkbox-group',
label: 'Checkbox Group',
name: 'checkbox-group-1500532701822',
values: [ [Object] ] } ]
The first problem is in the last entry of checkbox, the values should be
[{"label": "Option 1","value": "option-1","selected": true}]}]
but it only tunrs out to be object, this data is coming from an AJAX call from my client end where contentType is set to application/json; charset=utf-8.
The second problem is that when I try to insert this JSON data into Mongo, i am returned with an undefined error causing only the ID to be stored and none of the JSON components.
Note: If i insert a JSON array having only one element there is no problem. i need to store all this information together as it represents a form built using a formbuilder and I want to access all of the elements together.
Any help/advice would be greatly appreciated, thank you in advance. My code is as follows:
AJAX at client end:
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
data: ans,
traditional: true,
url: "/j",
success: function(){
console.log('success');
}
});
Insertion into Mongo at server end:
//FETCHING THE JSON OF THE CLAUSE FORM CREATED BY THE ADMIN
router.post('/j', function(req, res, next) {
req.session.fdata = req.body; //JSON FETCHED FROM
JAVASCRIPT USING AJAX, STORED IN SESSION
if(req.session.fdata==null) //CHECKING IF WE ARE RECEIVING VALUES
{
res.redirect('/admin');
}
else {
mongo.connect(url, function (err, db) {
assert.equal(null, err);
db.collection('clauses').insertOne(req.session.fdata, function (err, result) {
console.log('New Clause Added');
console.log(req.session.fdata3);
db.close();
});
});
res.redirect('/admin');
}
//console.log(req.session.fdata);
});