【问题标题】:Got 2 ways to store objects into MongoDB, one with destructuring the req.body and one without. Why destructuring then?有两种方法将对象存储到 MongoDB 中,一种是解构 req.body,另一种是不解构。那为什么要解构呢?
【发布时间】:2020-11-10 22:31:40
【问题描述】:

我正在编写一个制作活动创建应用程序的视频。 在视频中,伙计们为要保存到 Atlas 集群中的帖子编写控制器,如下所示:

exports.createPost = async (req, res) => {
  const { title, message, selectedFile, creator, tags } = req.body;
  const newPostMessage = new PostMessage({ title, message, selectedFile, creator, tags })
  try {
      await newPostMessage.save();
      res.status(201).json(newPostMessage );
  } catch (error) {
      res.status(409).json({ message: error.message });
  }
}

我在没有破坏正文的情况下编写了它:

exports.createPost = async (req, res) => {
  const post = req.body;
  const newPost = new PostMessage(post);
  try {
    await newPost.save();
    res.status(201).json(newPost)
  } catch (error) {
    res.status(409).json({
      message: error.message
    })
  }
};

在数据库中,我看到保存的 2 个结果完全相同。那么这里有什么区别呢?我为什么要破坏 req.body?

【问题讨论】:

    标签: node.js mongodb express mongodb-atlas


    【解决方案1】:

    我认为这只是个人喜好。有时使用解构更方便。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-28
      • 2011-06-23
      • 1970-01-01
      • 2016-03-29
      • 1970-01-01
      • 2019-12-10
      • 1970-01-01
      • 2019-08-27
      相关资源
      最近更新 更多