从集合返回的重复项目

时间:2020-05-30 09:34:46

标签: node.js mongodb express mongoose

博客架构:

{
        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' }}]
    }

喜欢添加赞的路线:

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也相同)。为什么会得到这样的结果?请注意,在我致电“喜欢路线”之后,我将我称为“博客路线”。

1 个答案:

答案 0 :(得分:0)

在我将“喜欢路线”更改为此后,效果很好:

fatal: [default]: FAILED! => {"changed": false, "msg": "The Python 2 bindings for rpm are needed for this module. If you require Python 3 support use the `dnf` Ansible module
instead.. The Python 2 yum module is needed for this module. If you require Python 3 support use the `dnf` Ansible module instead."}

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

相关问题