最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Mongoose Not Saving Data - Stack Overflow

programmeradmin0浏览0评论

I am having trouble with a simple query on my database. Following this tutorial: when Model.find() is called, he receives a JSON object back with the name field (the only custom field) and the _id and __v. When I do the same, all I receive back is the _id and __v field. I do get a successful response back saying the post was created, but it doesn't include the title or content fields. Yet a query shows that the data was never saved.

Routing and query:

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! Wele 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

        post.title = req.body.title; // Set title (from request)
        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({
                    message: "Post created!",
                    title: post.title,
                    content: post.content
                });
            }
        });
    })

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

        });
    });

module.exports = router;

Response:

[
    {
        "_id": "56a6adc31f06c4dc1cf82888",
        "__v": 0
    },
    {
        "_id": "56a9768888f806dc1fe45415",
        "__v": 0
    },
    {
        "_id": "56a97f3f4e269b7c21311df8",
        "__v": 0
    }
]

A db query in the shell returns the same information, just an _id and __v field.

I am having trouble with a simple query on my database. Following this tutorial: https://scotch.io/tutorials/build-a-restful-api-using-node-and-express-4 when Model.find() is called, he receives a JSON object back with the name field (the only custom field) and the _id and __v. When I do the same, all I receive back is the _id and __v field. I do get a successful response back saying the post was created, but it doesn't include the title or content fields. Yet a query shows that the data was never saved.

Routing and query:

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! Wele 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

        post.title = req.body.title; // Set title (from request)
        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({
                    message: "Post created!",
                    title: post.title,
                    content: post.content
                });
            }
        });
    })

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

        });
    });

module.exports = router;

Response:

[
    {
        "_id": "56a6adc31f06c4dc1cf82888",
        "__v": 0
    },
    {
        "_id": "56a9768888f806dc1fe45415",
        "__v": 0
    },
    {
        "_id": "56a97f3f4e269b7c21311df8",
        "__v": 0
    }
]

A db query in the shell returns the same information, just an _id and __v field.

Share Improve this question edited Jan 29, 2016 at 6:15 Jordan asked Jan 28, 2016 at 2:44 JordanJordan 9122 gold badges10 silver badges38 bronze badges 9
  • Why Post.remove({}); is called before Post.find()? – zangw Commented Jan 28, 2016 at 3:07
  • That was just some testing. I was trying to delete the collection before it started getting huge from me testing post operations over and over. It doesn't work though, how do I drop a collection when I never even made a collection. When I run post.save() what collection is it getting stored in? – Jordan Commented Jan 28, 2016 at 3:08
  • how do I drop a collection when I never even made a collection.? if there is no collection, why dope it? – zangw Commented Jan 28, 2016 at 3:15
  • 1 Given you connect to test db in your connection string. after post.save(). the post collection should be found under test db.. – zangw Commented Jan 28, 2016 at 3:17
  • 1 side note: before you do post.save() make sure to check if the item already exists in the database to avoid duplication – mugabits Commented Jan 28, 2016 at 7:15
 |  Show 4 more ments

6 Answers 6

Reset to default 3

I am beyond confused right now. It suddenly works, the code is the exact same as above. I am going to leave this open in case someone stumbles across it one day and can solve this mystery.

The problem is that you need to set the content-type while sending the post request as application/json otherwise the fields are not recognized.

I experienced an error like this.

The problem was that I was loading the wrong mongoose Schema.

The result is that the only fields that are saved are those that are present in both schemas, i.e. _id and __v.

For this code

post.title = req.body.title; // Set title (from request) post.content = req.body.content; // Set content (from request)

could you check

  1. req.body.title and req.body.content are not undefined?
  2. do you set the field in your Post schema as

    var PostSchema = new Schema({ title: String, content: String });

If you are using a manual tool like Postman to test your app, you must also put quotes around the key names in the body of your request, like {"key": "some string"}.

If you just put {key: "some string"} then the whole key/value pair is ignored when the document is saved to the database.

Exact same thing happened to me...

First two POSTs succeeded but did not post the data I was sending:

var p = new Post();
p.result = 'hello-world';

p.save(function (err) {});

Turned on debug mode: mongoose.set('debug', true); and next POST the field was saved...

Baffling!

发布评论

评论列表(0)

  1. 暂无评论