mongoose不保存数据

我遇到了一个简单的查询我的数据库的麻烦。 按照这个教程: https : //scotch.io/tutorials/build-a-restful-api-using-node-and-express-4当Model.find()被调用时,他会收到一个带有名称字段的JSON对象(唯一的自定义字段)和_id和__v。 当我这样做时,我所收到的是_id和__v字段。 我确实得到了一个成功的回应,说这个post是创build的,但是它不包含标题或内容字段。 然而,一个查询显示数据从未被保存过。

路由和查询:

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.title = req.body.title; // Set title (from request) post.content = req.body.content; // Set content (from request)

你能检查吗?

  1. req.body.titlereq.body.content不是undefined
  2. 您是否将Post模式中的字段设置为

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

如果您使用Postman这样的手动工具来testing您的应用程序,则还必须在请求正文中的键名称周围加上引号,如{"key": "some string"}

如果你只是把{key: "some string"}那么当文档被保存到数据库时,整个键/值对将被忽略。

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

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

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

打开debugging模式: mongoose.set('debug', true); 然后下一个post的领域被保存…

莫名其妙!