I have a promblem with saving data to db, mongoose saves empty object without value. Using mean stack.
controller: for example i send some "hello message"
$http({
method: 'POST',
url: '/api/message',
headers: {'Content-Type': 'application/json'},
data: JSON.stringify({msg: $scope.message})
}).
success(function(response) {
console.log("Success " + JSON.stringify(response));
}).
error(function(response) {
console.log("Error " + JSON.stringify(response));
});
server.js
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({'extended':'true'}));
app.use(bodyParser.json());
app.use(bodyParser.json({type: 'application/vnd.api+json'}));
var message = mongoose.model('Message', {
message: String
})
app.post('/api/message', function(req,res) {
var message = new Message(req.body);
message.save(function(err) {
if(err) throw err;
console.log(message);
})
res.status(200).send();
console.log(req.body);
})
my "hello" message reaches the server, but mongoose saves an empty object
{msg: "hello"} // console.log(req.body);
{"_id":"584ee18f169f902b7046e991","__v":0} // console.log(message);
what im doing wrong??
You have a mismatch between your request body and the Message definition. req.body contains a msg property, but Message is expecting a message property.
I would swap the following line in your angular controller:
data: JSON.stringify({msg: $scope.message})
To this:
data: JSON.stringify({message: $scope.message})
You could also update the Message model to have a property named msg instead of changing your angular code, if you'd prefer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With