首页 > 解决方案 > 使用邮递员将dataSchema发送到mongodb

问题描述

我用更多信息更新了这个问题:“我对 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 };

请问我做错了什么?

标签: node.jsmongodbexpressmongoosepostman

解决方案


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

请使用以下代码来允许 body-parser 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();
});

推荐阅读