简体   繁体   中英

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?

Somebody has an idea how to get just the new added object?

Unfortunately there is no option with findOneAndUpdate

You can do projection on original document but not on the updated document with findOneAndUpdate

I don't think there is no easy efficient way to do this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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