如何使用Koa API发布端点将数据添加到mongo数据库

时间:2019-05-14 10:33:16

标签: node.js reactjs mongodb mongoose koa

我正在尝试设置我的第一个Koa-React-Node-Mongo应用程序。我正在尝试创建端点,并将其发布到数据库中。

当我向使用{@ {1}}的Postman发送帖子时

http://localhost:3000/api/v1/posts/

我所有的帖子都返回:

{ "title": "This is a post", "urltitle":"first-post", "body": "Yabba yabba mega doo" }

这是我的职位要求的正文。

这是我的controllers / posts.js

Cannot POST /api/v1/posts/

这是我的models / posts.js

async function create(ctx) {
  try {
    const newPost = await new Post(ctx.request.body).save();
    ctx.body = post;
  } catch (err) {
    ctx.throw(422);
  }
}

和models / index.js

const mongoose = require('mongoose')

const schema = new mongoose.Schema({
  title: String,
  urltitle: String,
  body: String,
  lastupdated: { type: Date, default: Date.now },
  user: { type: mongoose.Schema.Types.ObjectId, ref: 'User' }
})

module.exports = mongoose.model('Post', schema)

0 个答案:

没有答案