【问题标题】:How to push reference and save via POST API in NodeJs?如何在 NodeJs 中通过 POST API 推送引用和保存?
【发布时间】:2018-09-20 18:52:17
【问题描述】:

为 MERN 堆栈应用程序使用 express.js 框架。这是我的第一个js 全栈应用程序,对很多这些功能都很陌生。需要POST 一个主题的新帖子并更新主题。引用 Posts 集合的帖子。

这里是server.js

router.post('/:id/posts', (req,res) => {
  const { id } = req.params // works

  const newPost = new Post({
    post: req.body.post,
    description: req.body.description,
    topic_id: id
  })

  const topic = Topic.findById(id).then(topics => res.json(topics))

  console.log(topic.posts)
  // and I don't understand why my topic object is always undefined I need to push a reference into it I think.

  //need to save/update topic object to db
  //need to save new post
  //my other post function has newPost.save().then(post => res.json(post) and it works. but in this function it doesn't. 
});

这是架构

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

如果有人能告诉我我做错了什么,我将不胜感激。如果需要更多信息,也推送到GitHub

第 31 行是代码 sn-p。

【问题讨论】:

    标签: javascript node.js express ecmascript-6 mern


    【解决方案1】:

    要保存,请执行以下操作:

    const topic = Topic.findById(id).then(topic => {
        topic.posts.push(newPost);
        topic.save(err => {
           if (err) {
             res.sendStatus(400)
           } else {
             res.sendStatus(200)
           }
        })
    })
    

    如果要将更新后的主题发送回客户端,可以在保存回调中通过主题ID查询。

    【讨论】:

    • 我相信我的帖子已经是这样了,请编辑原帖
    • 我也使用 Postman 检查是否使用 'newPost.save().then(post => res.json(post));'功能正常,我得到了主题 Json 作为响应,并且在我的控制台中收到了此错误消息。 UnhandledPromiseRejectionWarning: ValidationError: post validation failed: post: Path post is required., description: Path description is required.
    【解决方案2】:

    这行错了

    const topic = Topic.findById(id).then(topics => res.json(topics))
    

    在这里你正在做异步调用,所以主题将是一个承诺,而 topic.posts 将是未定义的(正常)

    看起来您使用 TypeScript 或 Ecmascript,所以您可以这样做:(查看 asyncawait 关键字)

    router.post('/:id/posts', async (req,res) => {
    
      const { id } = req.params // works
    
       const newPost = new Post({
         post: req.body.post,
         description: req.body.description,
         topic_id: req.body.id
       })
    
       try {
         const topic = await Topic.findById(id);
       }catch(err){
          // send a status 404 cause the id dont match any topic
          return;
       }
       console.log(topic.posts) //undefined but i still need to add post._id to my topic.posts 
    
         //attempt to save newPost object
       try {
         const post = await newPost.save();
         res.json(post);
       }catch(err){
          // You can send a internal error status cause something went wrong
       }
         // returns not post json but a topic json?
         // plus error
    });
    

    【讨论】:

    • 我替换了我的代码,但我收到了这个错误,我开始认为它是别的东西。 UnhandledPromiseRejectionWarning: ValidationError: post validation failed: post: Path post` 为必填项,描述:路径description 为必填项`
    • 是的,这是来自 mongoose 的典型错误消息,告诉您缺少某些内容。您是否尝试在 findById 之后更新主题?在这里它只是告诉你你“发布”必须有一个属性描述,所以也许 req.body.description 是空的
    • 我已经编辑了建议的解决方案,以包括我添加的内容。 newPost const 应该具有所需的“post”和“description”属性
    • 现在应该好了,我删除了 .then(post => res.json(post));从 findById 中,因为它正在将数据转换为未定义的原因 res.json 是一个无效函数,在这种情况下没有任何意义
    • 对不起,我觉得自己太笨了,它无法识别 catch 说:Unexpected token catch。在我必须查找一些文档之前,我从未见过 try and catch 语句。与此同时
    猜你喜欢
    • 2018-11-09
    • 2019-07-08
    • 2020-10-18
    • 1970-01-01
    • 2014-08-12
    • 1970-01-01
    • 2021-08-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多