简体   繁体   中英

Get newly embedded documents with mongoose

I use this to add embedded documents to a page

Page.findByIdAndUpdate(pageId, {
  $addToSet: {
    comments: {
      $each: comments
    }
  }
}, (err, page) => {
  // ...
});

When the comments are added to the Page model, they are given an id automatically.

I want to return these newly inserted comments after they have been given an id.

So I want something like

Page.findByIdAndUpdate(pageId, {
  $addToSet: {
    comments: {
      $each: comments
    }
  }
}, (err, page) => {
  return page.newlyAddedComments();
});

I know that one options could be to add the ids to the array comments before I insert them into the database, but I would want to omit this if possible.

Like @Shriram Manoharan said, there is no possibility to cut the embedded document with a find. You can do it with an aggregate but I thinks that its overkill.

If you want to get the last documents :

Use new in your find option (so it return the updated datas in page variable)

{ new: true }

and then slice the returned updated data to get only what you need. (Fresh added data would be in the end of the array)

Page.findByIdAndUpdate(pageId, {
  $addToSet: {
    comments: {
      $each: comments
    }
  }
}, { new: true }, (err, page) => {
  // Do not forget, what happend if _id is wrong?
  // if (!page) return ...; 
  return page.comments.slice(page.comments.length - comments.length - 1);
});

PS : I saw you use es6 syntax. I would recommand you to implement Promises in your code. I think it improve the reading and simplify the chaining of functions.

 Page.findByIdAndUpdate(pageId, {
      $addToSet: {
        comments: {
          $each: comments
        }
      }
    }, { new: true })
    .then(page => page.comments.slice(page.comments.length - comments.length - 1))
    .then(page => ...)
    .catch(err => ...);

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