【问题标题】:send dataSchema to mongodb using postman使用邮递员将dataSchema发送到mongodb
【发布时间】:2020-06-23 06:45:53
【问题描述】:

我用更多信息更新了这个问题:“ 我对 Express/mongodb 还很陌生,我正在尝试使用邮递员将我的 userSchema 发送到 mongoDb,但我收到此错误:"

这是我的主要脚本:

mongoose
  .connect(config.mongoURI, { useNewUrlParser: true, useUnifiedTopology: true })
  .then(() => console.log("db connected"))
  .catch(err => console.log(err));

app.use(cors());
app.options("*", cors());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(cookieParser());

app.post("/api/users/register", (req, res) => {
  const user = new User(req.body);
  user.save((err, userData) => {
    if (err) return res.json({ success: false, err });
  });
  return res.status(200);
});
app.listen(5000);

这是用户架构:

const mongoose = require("mongoose");

const userSchema = mongoose.Schema({
  name: {
    type: String,
    maxlength: 50
  },
  email: {
    type: String,
    trim: true,
    unique: 1
  },
  password: {
    type: String,
    minlength: 5
  },
  lastname: {
    type: String,
    maxlength: 50
  },
  role: {
    type: Number,
    default: 0
  },
  token: {
    type: String
  },
  tokenExp: {
    type: Number
  }
});

const User = mongoose.model("User", userSchema);

module.exports = { User };

请问我做错了什么?

【问题讨论】:

  • 首先将 GET 方法改为 postman 中的 POST。其次在正文中,请确保发送 JSON。第三,将return res.status(200); 行放在 if (err) 行之后
  • 可以在 Postman 中添加“正文”选项卡的屏幕截图吗?我怀疑您的 JSON 中有错误

标签: node.js mongodb express mongoose postman


【解决方案1】:

您使用的是 POST 请求,但您在 postman 中使用的是 GET 请求,因此最好将其更改为使用 async 和 await,因为服务器的响应可能需要一些时间,所以试试这个

app.post('/api/users/register', async (req, res) => {
const user = new User({

   //This comes from your schema 
   //I assumed you only have one schema named name
    name: req.body.name,

});
   try{
   const savedPost = await user.save();
   res.json(savedPost);
  } catch(err) {
   res.json({message: err})
  }
 });

【讨论】:

    【解决方案2】:

    您在 POST 方法中创建函数,但在 Postman 中您使用的是 GET 方法。请选择 POST 方式并尝试在 Postman 的 Body 内发送 Raw 数据。

    请使用以下代码来允许正文解析器 JSON 和方法。

    app.use(bodyParser.json({ type: 'application/*' }));
    app.use((req, res, next) => {
      res.header('Access-Control-Allow-Origin', "*");
      res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
      res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization, Access-Control-Allow-Credentials');
      res.header('Access-Control-Allow-Credentials', 'true');
      next();
    });
    

    【讨论】:

      猜你喜欢
      • 2022-01-25
      • 2020-04-07
      • 1970-01-01
      • 2015-03-21
      • 2015-09-02
      • 2019-06-15
      • 2016-02-03
      • 2018-05-30
      • 2022-01-25
      相关资源
      最近更新 更多