Bear Model
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var BearSchema = new Schema({
name: String
});
module.exports = mongoose.model('Bear', BearSchema);
server.js
var express = require('express'); // call express
var app = express(); // define our app using express
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
mongoose.connect('MONGO URI');
var Bear = require('./app/models/bear');
// configure app to use bodyParser()
// this will let us get the data from a POST
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var port = process.env.PORT || 8080; // set our port
// ROUTES FOR OUR API
var router = express.Router() // get an instance of the express Router
router.use(function(req, res, next) {
// do logging
console.log('Something is happening.');
next(); // make sure we go to the next routes and don't stop here
});
router.route('/bears')
.post(function(req, res) {
var bear = new Bear(); // create a new instance of the Bear model
bear.name = req.body.name; // set the bear name
// save the bear and check for errors
bear.save(function(err) {
console.log('Saving');
if (err)
res.send(err);
res.json({ message: 'Bear created!' });
});
});
// all of our routes will be prefixed with /api
app.use('/api', router);
// START THE SERVER
app.listen(port);
I am testing it with Postman in localhost and the parameter name gets passed to the bears route but then the save function doesnt do anything, neither saves the data or throws an error.
via Martin De Simone
No comments:
Post a Comment