发布请求不接收数据 - 表示js和mongo

时间:2016-12-12 20:16:07

标签: node.js mongodb express

我正在使用此代码:

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"
}

如何修复此问题以便它返回数据或者我是否需要首先创建架构并检查它?如果我可以指向正确的方向那将是伟大的

3 个答案:

答案 0 :(得分:1)

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

如果数据库中没有架构,那么您基本上会有一个装满(可能)不匹配的JSON对象的存储桶。因此,确保您的密钥与其预期值匹配将非常繁琐。

如果您是Mongo的新用户,我建议您查看Mongoose ODM。当试图理解NoSQL DB的结构和怪癖时,它会有所帮助。

答案 1 :(得分:0)

好..所以我创建了一个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帖子请求时:

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

req.body.firstName = undefined和req.params.firstName = undefined如何让它正确读取值?当我把静态字符串放在req.body的位置时......它很完美。

这是json目前的回报:

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

答案 2 :(得分:0)

>Hello,
>21 things matter the most on this problem,

1.you do not implement a body-parser
 here you can install it by: npm I body-parser

 app.use(express.json());
 app.use(bodyParser.urlencoded({extended:true}));
 app.use(bodyParser.json());


2.add content type in postman if you use postman to send API
Content-Type: application/JSON