【问题标题】:Mongoose Not Saving Data猫鼬不保存数据
【发布时间】:2016-05-05 06:22:48
【问题描述】:

我在对我的数据库进行简单查询时遇到问题。遵循本教程:https://scotch.io/tutorials/build-a-restful-api-using-node-and-express-4 当调用 Model.find() 时,他会收到一个 JSON 对象,其中包含 name 字段(唯一的自定义字段)以及 _id 和 __v。当我这样做时,我收到的只是 _id 和 __v 字段。我确实收到了成功的回复,说帖子已创建,但它不包括标题或内容字段。然而查询显示数据从未保存。

路由和查询:

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;

回复:

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

shell 中的 db 查询返回相同的信息,只是一个 _id 和 __v 字段。

【问题讨论】:

  • 为什么Post.remove({});在Post.find()之前被调用?
  • 这只是一些测试。我试图在它开始变得庞大之前删除该集合,因为我一遍又一遍地测试后期操作。但它不起作用,当我什至从未制作过收藏时,我该如何放弃收藏。当我运行 post.save() 时,它会存储在哪个集合中?
  • how do I drop a collection when I never even made a collection.?如果没有收藏,为什么要收藏它?
  • 假设您在连接字符串中连接到 test db。在post.save() 之后。 post 集合应该在 test db..下找到。
  • 附注:在您执行 post.save() 之前,请确保检查该项目是否已存在于数据库中以避免重复

标签: javascript node.js mongodb express mongoose


【解决方案1】:

我现在很困惑。它突然起作用了,代码与上面完全相同。我将把它打开,以防有一天有人偶然发现它并能解开这个谜。

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

      我遇到了这样的错误。

      问题是我加载了错误的 mongoose Schema。

      结果是唯一保存的字段是两个模式中都存在的字段,即_id 和__v。

      【讨论】:

        【解决方案4】:

        对于这个代码

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

        你可以检查一下

        1. req.body.title 和 req.body.content 不是 undefined?
        2. 您是否将 Post 架构中的字段设置为

          var PostSchema = new Schema({ 标题:字符串, 内容:字符串 });

        【讨论】:

          【解决方案5】:

          如果您使用 Postman 等手动工具来测试您的应用,您还必须在请求正文中的键名周围加上引号,例如 {"key": "some string"}。

          如果您只是输入{key: "some string"},那么在将文档保存到数据库时会忽略整个键/值对。

          【讨论】:

            【解决方案6】:

            完全一样的事情发生在我身上......

            前两个 POST 成功,但没有发布我发送的数据:

            var p = new Post();
            p.result = 'hello-world';
            
            p.save(function (err) {});
            

            打开调试模式:mongoose.set('debug', true); 和下一个 POST 字段已保存...

            莫名其妙!

            【讨论】:

              猜你喜欢
              • 2013-12-08
              • 1970-01-01
              • 2022-01-24
              • 2020-01-26
              • 2018-07-12
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多