Ilijanovic
Ilijanovic

Reputation: 14904

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?

Upvotes: 2

Views: 365

Answers (1)

Gibbs
Gibbs

Reputation: 22956

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.

Upvotes: 1

Related Questions