Jordan
Jordan

Reputation: 912

Mongoose Saving Incorrect Values

When creating an object from a post request, both of the fields that come from the request body are being set to the field name itself. I am not getting any errors but I am also not getting the expected JSON object of the request body back in the response. I was using a local mongodb instance but now I am using a mongolab database, thought it would maybe solve the problem but nothing changed.

var express = require("express");
var router = express.Router();
var Post = require("../app/models/post.js");

/*
//Drop Post collection
Post.remove({}, function(err, num_docs) {
    if (err) {
        res.send(err);
    } else {
        console.log("Collection dropped, documents deleted: " + num_docs);
    }
});
*/

// Middleware for all routes.
router.use(function(req, res, next) {
    console.log("API request made.");
    next(); // Go to next routes, don't stop here
});

// Test route to ensure routing is working
router.get("/", function(req, res) {
    res.json({
        message: "Hooray! Welcome to the API!"
    });
});

// On routes that end in /posts
router.route("/posts")
    // Create post. (Accessed at POST http://localhost/api/posts)
    .post(function(req, res) {

        var post = new Post(); // Create new instance of post model

        if (req.body.title !== undefined) {
            post.title = req.body.title; // Set title (from request)
        }
        if (req.body.content !== undefined) {
            post.content = req.body.content; // Set content (from request)
        }

        // Save the post, and check for errors.
        post.save(function(err) {
            if (err) {
                res.send(err);
            } else {
                res.json(req.body);
            }
        });

    })

    .get(function(req, res) {
        Post.find({}, { "__v": 0, "_id": 0 }).exec(function(err, posts) {
            if(err) {
                res.send(err);
            } else {
                res.json(posts);
            }

        });
    });

module.exports = router;

Request JSON:

{
    "title": "sample title",
    "content": "sample content"
}

Output:

[
    {
        "lastUpdated": "2016-01-29T07:26:01.810Z",
        "uploadDate": "2016-01-29T07:26:01.810Z",
        "content": "content",
        "title": "title"
    }
]

Upvotes: 1

Views: 213

Answers (1)

jack blank
jack blank

Reputation: 5195

You can't use req.body without including body parser and expect req.body to produce the expected result in express. Did you do npm install body-parser. I don't see you requiring body-parser in your code. Maybe you included body-parser in your main file. I believe that if you don't use it req.body will be empty.

add this below your other requires

var bodyParser = require("body-parser");

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

app.use(bodyParser.json())

and don't forget to do npm install body-parser in your terminal.

Upvotes: 2

Related Questions