在保存后使用mongoose的lean方法

3

我想给返回的post添加一个键,但是我似乎无法让lean()起作用。我该如何在保存后操作返回的帖子?

我想也许我需要将findById中加入lean,像这样Post.findById(req.params.id).lean().then()。但那没用,而且只会使第一个初始帖子可变。它会说:

post.save不是一个函数

如果我像这样做:Post.findById(req.params.id).lean().then()也是一样的。

我只想返回即将发送回客户端的对象,我不想将键保存在实际文档中。

 Post.findById(req.params.id)
      .then(post => {
        if (
          post.likes.filter(like => like.user.toString() === req.user.id)
            .length === 0
        ) {
          return res
            .status(400)
            .json({ notliked: "You have not yet liked this post" });
        }

        // Get remove index
        const removeIndex = post.likes
          .map(item => item.user.toString())
          .indexOf(req.user.id);

        // Splice out of array
        post.likes.splice(removeIndex, 1);

        // Save
        post.save().then(post => {  
          post["liked"] = false;  <-------
          res.json(post);
        });
      })

edit

  Post.findById(req.params.id)
      .lean()
      .then(post => {
        if (
          post.likes.filter(like => like.user.toString() === req.user.id)
            .length === 0
        ) {
          return res
            .status(400)
            .json({ notliked: "You have not yet liked this post" });
        }

        // Get remove index
        const removeIndex = post.likes
          .map(item => item.user.toString())
          .indexOf(req.user.id);

        // Splice out of array
        post.likes.splice(removeIndex, 1);
        post["liked"] = false;
        res.json(post);
        // Save
        post.save();
      })

出现错误

post.save不是一个函数


你想要更新文档还是针对请求的用户返回 liked 的真或假? - Ashh
我想保存已修改的数组的更新文档,然后在响应体中改变post。 - Snoopy
1个回答

1

您可以通过在 likes 数组中搜索 req.user.id 来轻松完成此操作。

Post.findOne({ _id: req.params.id }).lean().then((post) => {
  if (post.likes.indexOf(req.user.id) !== -1) {
    post.isLiked = true
  }
  post.isLiked = false
  res.json(post)
})

更好的聚合。
Post.aggregate([
  { "$match": { "_id": mongoose.Types.ObjectId(req.user.id) }},
  { "$addFields": {
    "isLiked": { "$in": [mongoose.Types.ObjectId(req.user.id), "$likes"] }
  }}
])

编辑:如果您想更新文档,请使用更新查询

Post.findOneAndUpdate(
  { _id: req.params.id },
  { $pull: { likes: { user: req.user.id } }},
  { new: true }
).then((post) => {
  res.json(post)
})

喜欢的帖子模式

...
    likes: [
        {
          user: {
            type: Schema.Types.ObjectId,
            ref: "users"
          }
        }
      ]
...

我编辑了我的问题并在保存之前突变了“post”,然后将其作为响应发送回去,仍然得到post.save不是一个函数的错误。我将不得不研究聚合,但是想使用第一种方法。 - Snoopy
你不需要使用.save,因为你不想更新文档。只需按照我的第一个查询即可。 - Ashh
我在回答你的原始问题时澄清了我的意思。抱歉。 - Snoopy
1
更新了我的回答。 - Ashh
谢谢您,我已经添加了我的模式,这样我所做的编辑对其他人来说就有意义了。 - Snoopy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接