I write a simple application using the MEAN stack, when I send a message to the server, such as "hello", an empty object is saved in the database.
controller:
$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:
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); }) This is what I get in the console:
{msg: "hello"} // console.log(req.body); {"_id":"584ee18f169f902b7046e991","__v":0} // console.log(message);
var Message = mongoose.model(..)andvar message = new Message({message:req.body});- Yura Ivanovvar Message = mongoose.model('Message', {message: String})a capital model must be declared. You then donew Messagewith a capital letter, the register matters. - Yura Ivanovreq.body. - Yura Ivanov