请求不要接收数据 – 表示js和mongo

我正在使用这个代码:

app.post("/users", function(req, res) { db.collection(USERS_COLLECTION).insertOne(req.body , function(err, doc) { if (err) { handleError(res, err.message, "Failed to create new user."); } else { res.status(201).json(req.body); } }); }); 

我试图把这个请求:localhost:8080 / users?firstName = foo&lastName = bar

但是当我在postman中尝试post请求时,它只返回一个id,并不会在数据库中插入params。

 { "_id": "584f04eb141faa7df7fc4059" } 

我该如何解决这个问题,以便它返回数据,或者我需要先创build一个模式,并检查它? 如果我能指出一个好的方向

你是正确的,你需要一个架构!

如果数据库中没有模式,那么基本上就会有一个桶充满(可能)不匹配的JSON对象。 因此,确保您的密钥与预期值相匹配是很繁琐的。

如果您是Mongo的新手,我build议您查看Mongoose ODM。 它有助于理解NoSQL DB的结构和怪癖。

好吧,所以我创build了一个Schema

 var mongoose = require('mongoose'); // user schema var usersSchema = mongoose.Schema({ firstName: String, lastName : String, email : String }); mongoose.model('users', usersSchema); 

和发布请求代码如下所示:

 var express = require("express"); var path = require("path"); var bodyParser = require("body-parser"); var mongodb = require("mongodb"); var ObjectID = mongodb.ObjectID; var USERS_COLLECTION = "users"; var mongoURL = "the url is here"; var user = require("./Models/User"); var mongoose = require('mongoose'); var app = express(); app.use(express.static(__dirname + "/public")); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); mongoose.connect(mongoURL); // USERS API ROUTES BELOW // Generic error handler used by all endpoints. function handleError(res, reason, message, code) { console.log("ERROR: " + reason); res.status(code || 500).json({"error": message}); } /* "/USERS" * POST: creates a new user */ app.post("/users", function(req, res) { var firstName = req.params.firstName; var lastName = req.params.lastName; var email = req.params.email; //call the create function for our database mongoose.model('users').create({ firstName : firstName, lastName : lastName, email : email }, function (err, user) { if (err) { res.send("There was a problem adding the information to the database."); } else { //User has been created console.log('POST creating new users: ' + user + firstName); res.format({ //JSON response will show the newly created user json: function(){ res.json(user); } }); } }) }); 

虽然问题是,当我发送一个http post请求:

 localhost:8080/users?firstName=foo&lastName=bar&email=foobar@gmail.com 

req.body.firstName = undefined和req.params.firstName = undefined如何让它正确读取值? 当我把静态string放在req.body的地方…它的工作完美。

这是目前在json中返回的内容:

 { "__v": 0, "_id": "5851567048018fa141543f53" }