首页 > 解决方案 > 从集合返回的重复项目

问题描述

博客架构:

{
        body: { type: String, required: true },
        title: { type: String, required: true },
        published: { type: String, default: false },
        date: { type: Date, default: Date.now },
        user: { type: Schema.Types.ObjectId, ref: 'BlogUser' },
        comments: [{ type: Schema.Types.ObjectId, ref: 'Comments' }],
        likes:[{user:{ type: Schema.Types.ObjectId, ref: 'BlogUser' }}]
    }

Like Route 用于添加点赞:

exports.likeBlog = async (req, res) => {
  const blog_id = req.params.blog_id;
  const user_id = req.body.user_id;
  await Blog.findByIdAndUpdate(
    blog_id,
    {
      $push: {
        likes: {
          user: user_id,
        },
      },
    },
    { new: true },
    (err, newBlog) => {
      if (err) res.status(422).json(err);
      console.log(newBlog);
      res.json(newBlog);
    }
  );
};

接收博客的博客路径:

exports.getBlogByID = async (req, res) => {
  const blog_id = req.params.blog_id;
  try {
    const blog = await Blog.findById(blog_id)
      .populate("comments")
      .populate("user");
    console.log(blog);
    res.json(blog);
  } catch (error) {
    res.status(401).json(error);
  }
};

当我通过从客户端调用添加一个喜欢时Like route,我得到一个具有正确数量的博客,即只有 1 个。但是当我从它请求博客时, Blog Route它返回我在“喜欢”数组中的两个对象,它们彼此相同(相同的 id也)。为什么我会得到这样的结果?请注意,我在调用“Like Route”之后调用了“Blog Route”。

标签: node.jsmongodbexpressmongoose

解决方案


在我将“like route”更改为此之后,它运行良好:

exports.likeBlog = async (req, res) => {
  const blog_id = req.params.blog_id;
  const user_id = req.body.user_id;
  const blog = await Blog.findById(blog_id);
  blog.likes.unshift({ user: user_id });
  await blog.save();
  Blog.findById(blog_id)
    .then((result) => {
      res.json(result);
    })
    .catch((error) => {
      res.status(501).json({ error });
    });
};

我仍然不知道两者之间有什么区别。


推荐阅读