简体   繁体   English

mongoose 使用 findOneAndUpdate 并且只返回数组中更新的元素

[英]mongoose use findOneAndUpdate and only return the updated element in array

I have following problem:我有以下问题:

  let post = await User.findOneAndUpdate(
    { _id: USER_ID },
    {
      $push: {
        posts: {
          title,
          content,
          userId: USER_ID,
          titleUrl,
          thumbnail: {
            webp: WEBP_PATH,
            jpeg: JPEG_PATH,
            placeholder: PLACEHOLDER
          }
        }
      }
    },
    { new: true }
  );

This query almost works well.这个查询几乎可以正常工作。 The problem is whenever i push an item to the array i want to get the updated element back.问题是每当我将一个项目推送到数组时,我都想取回更新的元素。 Unfortunetally i get the whole document with all the posts in the array.不幸的是,我得到了包含数组中所有帖子的整个文档。 Sure i could do something like posts.slice(-1) but i think this is super inefficient to load everything if i just need 1 element isnt it?当然我可以做类似posts.slice(-1)的事情,但我认为如果我只需要1个元素,那么加载所有内容的效率非常低,不是吗?

Somebody has an idea how to get just the new added object?有人知道如何获得新添加的 object?

Unfortunately there is no option with findOneAndUpdate不幸的是findOneAndUpdate没有选项

You can do projection on original document but not on the updated document with findOneAndUpdate您可以使用findOneAndUpdate对原始文档进行projection ,但不能对更新的文档进行投影

I don't think there is no easy efficient way to do this.我认为没有简单有效的方法可以做到这一点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM