I'm trying to do:
$.ajax({
type:"POST",
url:"/psychos",
data:JSON.stringify(this.psycho)
})
At server I got:
app.post("/psychos", function(request, response) {
var psychologist = request.body.psycho
console.log(psychologist)
psicologosCollection.insert(psychologist, function(error, responseFromDB) {
if (error) {response.send(responseFromDB)}
console.log("Se ha insertado: "+ JSON.strinfigy(responseFromDB))
response.send(responseFromDB)
})
})
But, the console.log()
is printing undefined
and got the following throw:
TypeError: Cannot read property '_id' of undefined
at insertWithWriteCommands (/home/diegoaguilar/DigitalOcean/psicologostuxtepec/node_modules/mongodb/lib/mongodb/collection/core.js:78:13)
at Collection.insert (/home/diegoaguilar/DigitalOcean/psicologostuxtepec/node_modules/mongodb/lib/mongodb/collection/core.js:30:7)
at Object.handle (/home/diegoaguilar/DigitalOcean/psicologostuxtepec/server.js:117:25)
at next_layer (/home/diegoaguilar/DigitalOcean/psicologostuxtepec/node_modules/express/lib/router/route.js:103:13)
at Route.dispatch (/home/diegoaguilar/DigitalOcean/psicologostuxtepec/node_modules/express/lib/router/route.js:107:5)
at c (/home/diegoaguilar/DigitalOcean/psicologostuxtepec/node_modules/express/lib/router/index.js:195:24)
at Function.proto.process_params (/home/diegoaguilar/DigitalOcean/psicologostuxtepec/node_modules/express/lib/router/index.js:251:12)
at next (/home/diegoaguilar/DigitalOcean/psicologostuxtepec/node_modules/express/lib/router/index.js:189:19)
at next (/home/diegoaguilar/DigitalOcean/psicologostuxtepec/node_modules/express/lib/router/index.js:166:38)
at Layer.session [as handle] (/home/diegoaguilar/DigitalOcean/psicologostuxtepec/node_modules/express-session/index.js:98:29)
I'm using BodyParser
before:
var bodyParser = require('body-parser')
app.use(bodyParser())
psycho is actually a valid existing object. At the method where AJAX is performed a console.log(this.psycho)
will print my object. What am I doing wrong?
Edit:
Even I found out I should have got:
var psychologist = request.body.psycho
at server GET route code, I can't understand how bodyParser generates an Object?
For a quite similar AJAX call I tried before:
function getSendingJSON(url,reqObject,callBack) {
$.ajax({
type: "get",
data: reqObject,
dataType: "json",
url: url,
success: function(response){
callBack(response);
}
});
}
So response was a JSON, and callback function looked similar to:
function plotReglaFalsa(respuesta) {
if (respuesta.fail) {...}
else if (respuesta.negative) {...}
....
}
Even that was purely at client side, I'm confused how to deal with Objects/JSON serialization and how bodyParser acts for it.