I'm trying to add some data to database on mongolab.com I have a app written using node.js
part of index.js
is:
var express = require('express');
var app = express();
var router = express.Router();
var mongoose = require('mongoose');
var StacjaMeteo = require('./models/StacjaMeteo.js');
mongoose.connect('mongodb://user:xxxxxxxx@ds041484.mongolab.com:41484/stacjameteo', function(err) {
if(err) {
console.log('connection error', err);
}
else {
console.log('connection with database successful');
}
});
app.set('port', (process.env.PORT || 5000));
app.post('/meteo', function(req, res, next) {
StacjaMeteo.create(req.body, function(err, post) {
if(err) return next(err);
res.json(post);
});
});
The mongoose model looks like this: models/StacjaMeteo.js
var mongoose = require('mongoose');
var StacjaMeteoSchema = new mongoose.Schema({
winddir: Number,
windspeedmph: Number,
windgustmph: Number,
windgustdir: Number,
humidity: Number,
tempf: Number,
pressure: Number,
updated_at: {type: Date, default: Date.now}
});
module.exports = mongoose.model('StacjaMeteo', StacjaMeteoSchema);
After lunching the app I got info that connection with database is successful. But when I'm trying to send some data to it using Postman:
POST /meteo HTTP/1.1
Host: localhost:5000
Cache-Control: no-cache
Postman-Token: 39ec83eb-00e9-3e69-875e-ef8f2eaf2b1a
Content-Type: application/x-www-form-urlencoded
winddir=0&windspeedmph=0&windgustmph=0&humidity=0&tempf=0&pressure=0
I got the respond:
{
"__v": 0,
"_id": "567012cbc1e781f67706f9ad",
"updated_at": "2015-12-15T13:16:59.964Z"
}
So there is nothing more than just the id and updated_at and nothing new is added to database.
What Am I doing wrong?
You didnt tell express how to parse your request body.
In your express configuration , add this two lines
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({extended: false}));
More info on extended keyword : https://www.npmjs.com/package/body-parser#extended
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.