创建发布路线以为其关系添加引用

时间:2018-09-20 03:23:26

标签: express mongoose mern

我已经基本运行了MERN Stack应用程序,可以分别执行GET,POST和Delete Topics和Post,它们在Schema中具有关系,但是我不知道如何在POST时正确地路由它以合并这些关系。

const express = require('express');
const router = express.Router();

 const Post = require("../../models/Post");
 const Topic = require('../../models/Topic');

router.post("/", (req,res) => {
  //gets topic id from param
const {topic} = req.params;
  //creating a new post
const newPost = new Post({
    post: req.body.post,
    description: req.body.description,
    topic_id: req.body.topic_id
});
  //get topic by id
const topic_obj = Topic.findById(topic);
  //add posts to topic_object 
topic_obj.posts.push(newPost);
  //and save
topic_obj.save()
    .then(newPost.save()
    .then(post => res.json(post)).catch(err => console.log(err)));
});
module.exports = router;

我不知道您是否需要更多信息 我将其推送到GitHub寻求帮助L https://github.com/wolffles/bloccit-node/blob/react/routes/api/posts.js

1 个答案:

答案 0 :(得分:0)

根据TopicSchema

const TopicSchema = new Schema({
topic: {
    type: String,
    required: true
},
description: {
    type: String,
    required: true
},
posts: [
    { 
        type: Schema.Types.ObjectId,
        ref: 'post'
    }
],
date: {
    type: Date,
    default: Date.now
}});

要合并TopicPost之间的关系,您需要向_id的{​​{1}}字段中添加新创建的Post对象的posts属性新创建的Topic代表的对象。

Post

编辑: 您的代码中存在一些导致错误的问题。

  1. topic_obj.posts.push(newPost._id); 您应验证const {topic} = req.params;是否为有效的topic
  2. 您还应该验证请求正文,并检查ObjectIddescription是否具有必需的格式。
  3. 您通过将post id传递给请求正文并作为请求参数来对其进行伪装。
  4. Topic这是一个 async 操作,它返回const topic_obj = Topic.findById(topic);而不是查询结果。

代码应类似于(未经测试):

Promise