Reputation: 201
var myobj= { school: true, address: false };
var myArray = [];
myArray.push(myobj);
updateSchool(myArray);
function updateSchool(thisSchool) {
$.ajax
({
type: "POST",
url: '/update_school',
data: {
school: thisSchool,
},
}
})
in App.js:
app.post('/update_school', function(request, response) {
......
dbo.collection("School").updateOne({_id: request.session.username},{$set:
{School:request.body.school}}, function(err, result){
...... }
}
In mongodb boolean values stores as a string like [{school:"true", address:"false"}]
Could anyone help me how to store as a Boolean values in mongodb. Thanks.
Upvotes: 1
Views: 1133
Reputation: 3842
When you pass an object to in $.ajax()
data
, it will be converted to URL encoded string (application/x-www-form-urlencoded
) which doesn't recognize boolean data type. From the doc:
When data is an object, jQuery generates the data string from the object's key/value pairs unless the processData option is set to false. For example, { a: "bc", d: "e,f" } is converted to the string "a=bc&d=e%2Cf"
So in order to have the boolean saved properly you need to parse it manually in the server or send the payload as JSON (application/json
). This is how to do the latter in jquery:
function writeObj(obj) {
document.write('<pre>' + JSON.stringify(obj, null, 4) + '</pre>');
}
function updateSchool(thisSchool) {
$.ajax({
type: "POST",
// url: '/update_school',
url: 'https://httpbin.org/anything',
contentType: 'application/json',
data: JSON.stringify({
school: thisSchool,
}),
})
.done(writeObj)
.fail(writeObj);
}
var myobj = {
school: true,
address: false
};
var myArray = [];
myArray.push(myobj);
updateSchool(myArray);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Upvotes: 2