简体   繁体   中英

Mongoose Not Saving Data

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

        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 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.

问题是您需要在将发布请求作为application/json发送时设置content-type ,否则无法识别字段。

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, ie _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!

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