使用mongoose获取新嵌入的文档

时间:2016-09-21 04:47:36

标签: javascript arrays node.js mongodb mongoose

我用它来将嵌入文档添加到页面

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

将评论添加到Page模型后,系统会自动为id提供评论。

我想在获得id之后返回这些新插入的评论。

所以我想要像

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

我知道在将数据插入数据库之前,可以将一个选项添加到数组comments,但如果可能的话我想省略它。

1 个答案:

答案 0 :(得分:0)

就像@Shriram一样,Manoharan说,没有可能用查找来剪切嵌入文档。你可以用聚合来做,但我认为它有点矫枉过正。

如果您想获取最后的文件

在查找选项中使用new(因此它会在页面变量中返回更新的数据)

{ new: true }

然后将返回的更新数据切片以仅获得所需内容。 (新添加的数据将在数组的末尾)

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 :我看到你使用es6语法。我建议你在代码中实现Promises。我认为它改善了阅读并简化了函数的链接。

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