Node.js 使用邮递员将dataSchema发送到mongodb

Node.js 使用邮递员将dataSchema发送到mongodb,node.js,mongodb,express,mongoose,postman,Node.js,Mongodb,Express,Mongoose,Postman,我将用更多信息更新问题:” 我是Express/mongodb的新手,我正在尝试使用postman将我的userSchema发送到mongodb,但我遇到了以下错误: 这是我的主要剧本: mongoose .connect(config.mongoURI, { useNewUrlParser: true, useUnifiedTopology: true }) .then(() => console.log("db connected")) .catch(err =>

我将用更多信息更新问题:” 我是Express/mongodb的新手,我正在尝试使用postman将我的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 };

请问我做错了什么

您使用的是POST请求,但在postman中使用的是GET请求,因此最好使用async和Wait,因为从服务器响应可能需要一些时间,所以请尝试此方法

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})
  }
 });

在POST方法中创建函数,但在Postman中使用的是GET方法。请选择POST方法,并尝试在Postman中发送身体内部的原始数据

请使用以下代码来允许主体解析器和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();
});

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