简体   繁体   中英

RESTfull services, Post cannot save properly to db

RESTfull services, Post cannot save properly to db

I have node+express+mongoose My model:

var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var bookModel = new Schema({
title: { type: String },
author: { type: String },
genre: { type: String },
read:{ type: Boolean, default:false }   
});
module.exports = mongoose.model('Book', bookModel);

My App.js

var express = require('express'),
mongoose = require('mongoose'),
bodyParser = require('body-parser');

var db = mongoose.connect('mongodb://localhost/bookApi');
var Book = require('./models/bookModel');
console.log(Book);

var app = express();

var port = process.env.PORT || 3000;

app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());

bookRouter = require('./Routes/bookRoutes')(Book);

app.use('/api/books', bookRouter);
/*app.use('/api/authors', authorRouter);*/

app.get('/', function (req, res) {
    res.send('welcome to my API!');
});


app.listen(port, function () {
    console.log('Gulp running on Port: ' + port);
});

My Routes:

var express = require('express');


var routes = function(Book){
    var bookRouter = express.Router();

bookRouter.route('/')
    .post(function(req, res){
        var book = new Book(req.body);

        book.save();
        res.status(201).send(book);

    })
    .get(function (req, res) {
        var query = {};
        if(req.query.genre){
            query.genre = req.query.genre;
        }

        Book.find(query, function (err, books) {
            if(err)
                res.status(500).send(err);
            else
                res.json(books);
        });
    });
bookRouter.route('/:bookId')
    .get(function (req, res) {

        Book.findById(req.params.bookId, function (err, book) {
            if(err)
                res.status(500).send(err);
            else
                res.json(book);
        });
    })
    .put(function (req, res){
        Book.findById(req.params.bookId, function (err, book) {
            if(err)
                res.status(500).send(err);
            else
                book.title = req.body.title;
                book.author = req.body.author;
                book.genre = req.body.genre;
                book.read = req.body.read;
                book.save();
                res.json(book);
        });
            });

    return bookRouter;
};
module.exports = routes;

I'm using Postmant to test I can get all info, but when I'm trying to post something like

{"title":"WAR","genre":"Sience Fiction","author":"Wells","read":false}

I'm getting back body: {"_id":"5629377429d3c1088c0ebf37","read":false} So from book model only last param is in the body,

Can you please just take a look if I'm missing something

You could display what you received in your application on a POST method. I mean: printing the content of the variable req.body . I guess that it's empty.

I think that you miss the Content-Type header when you did the call from Postman. I reproduced your problem without the header and it works with the header. Here is the request I used to make your code works:

POST /api/books/ HTTP/1.1
Content-Type: application/json

{"title":"WAR","genre":"Sience Fiction","author":"Wells","read":false}

And the corresponding response:

HTTP/1.1 201 Created
X-Powered-By: Express
Content-Type: application/json; charset=utf-8
Content-Length: 111
ETag: W/"6f-25V+nQZe0YZPysuvDsoa5Q"
Date: Fri, 23 Oct 2015 07:34:43 GMT
Connection: keep-alive

{"__v":0,"title":"WAR","genre":"Sience Fiction","author":"Wells","_id":"5629e313074a746934d55f40","read":false}

In fact the body-parser module needs this hint to know how to process the content. If you want to support a default content type (I mean if the header isn't present - in fact, it should be there), you could add an Express middleware to set a content type in the request if any.

Otherwise, one small remark regarding your code. You could update it to leverage callback within the save method:

bookRouter.route('/')
  .post(function(req, res){
    var book = new Book(req.body);

    book.save(function(err, savedBook) {
      res.status(201).send(savedBook);
    });
  })

Hope it helps you, Thierry

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM