【问题标题】:_doc in request body请求正文中的 _doc
【发布时间】:2021-07-07 08:17:21
【问题描述】:

我正在尝试将由 MongoDB 模型创建的对象作为发布请求的主体发送到一个开玩笑的测试中。 这是测试:

test("post request successfully creates a new blog", async () => {
  const newBlog = new Blog({
    title: "My mundane day at home 3",
    author: "AbG",
    url: "https://www.google.co.in/",
    likes: 11,
  });
  await api
    .post("/api/blogs")
    .send(newBlog)
    .expect(201)
    .expect("Content-Type", /application\/json/)
    .catch((err) => console.log(err));
  const blogs = await Blog.find({});
  expect(blogs).toHaveLength(initialBlogs.length + 1);
});

如您所见,我将 newBlog 作为请求正文发送。但是当我在控制器中收到它时,newBlog 出现在 request.body._doc 而不是 request.body 中。 我认为这与博客的猫鼬模型有关。

const blogSchema = new mongoose.Schema({
  title: {
    type: String,
    required: true,
  },
  author: {
    type: String,
    required: true,
  },
  url: {
    type: String,
    required: true,
  },
  likes: {
    type: Number,
    required: false,
    default: 0,
  },
});
module.exports = mongoose.model("Blog", blogSchema);

我不明白为什么会这样。

【问题讨论】:

  • 本次讨论是否回应了您的问题? stackoverflow.com/questions/48989100/…
  • ĐăngKhoaĐinh 这个问题与我的问题类似。尽管解决方案不一样,但我设法找到了解决方案。感谢您的帮助!

标签: node.js express mongoose jestjs


【解决方案1】:

我发现我哪里出错了。 在测试用例中,我创建了一个 mongodb 模式实例并将其作为请求体而不是普通的 JS 对象传递。在 express 应用程序中,我试图将请求正文作为 JS 对象访问。所以造成了混乱。 我所做的更改: 在测试中: 而不是

const newBlog = new Blog({....})

我做到了

const newBlog = {....}

因此,我避免将 mongodb 对象作为请求主体传递,并在我需要它之前立即使用构造函数创建了 mongodb 对象。 发帖路线如下:

blogsRouter.post("/", async (request, response) => {
  const blog = new Blog(request.body);
  const savedBlog = await blog.save();
  response.status(201).json(savedBlog);
});

【讨论】:

    猜你喜欢
    • 2021-12-17
    • 2019-08-19
    • 2021-01-10
    • 2019-06-26
    • 1970-01-01
    • 2016-12-13
    • 2017-07-10
    • 1970-01-01
    • 2016-08-24
    相关资源
    最近更新 更多