如何返回最后一个push()嵌入式文档 [英] How to return the last push() embedded document
问题描述
我一直试图找出是否可行.
I'm stuck trying to figure out if this is possible.
使用猫鼬的博客示例进行演示,但是我的实际用例稍微复杂一些:
Using the blog example from mongoose to demonstrate, however my actual use case is slightly more complicated:
var Comments = new Schema({
title : String
, body : String
, date : Date
});
var BlogPost = new Schema({
author : ObjectId
, title : String
, body : String
, date : Date
, comments : [Comments]
});
var BlogPost = mongoose.model('BlogPost');
var post = new BlogPost();
我需要创建一个新评论并将 new 评论返回给客户端.将注释作为嵌入式文档确实对我来说很方便,并且效果很好.但是,我不想每次添加新评论时都将每条评论都返回给客户端.
I need to create a new comment and return the new comment to the client. Having comments as embedded document is really convenient for me and works well. However I don't want to return every single comment to the client each time I add a new one.
post.comments.push({ title: 'My comment' });
在我使用猫鼬的过程中,我想知道如何获得新注释的id
,这将有所帮助,并允许我添加其他功能,例如编辑注释或删除注释.
As I'm using mongoose if I could some how get the id
of the new comment that would help and also allow me to add other functionality such as editing a commenting or deleting a comment.
唯一的方法就是将评论作为自己的收藏吗?
Is the only way to do this is to have comments as their own collection?
推荐答案
我想您要解决的问题是在客户发表评论后如何更新页面,对吗?
I guess that the problem you're trying to solve is to how to update the page after a client posts a comment, right?
因此,您要插入一个新注释.这意味着您已经有了它的数据.执行插入并将数据返回给客户端.或者,更好的是,返回一个简单的确认,因为客户端也具有完整的注释数据并可以单独呈现.
So, you're inserting a new comment. This means that you already have its data. Perform an insert and return the data to the client. Or, better yet, return a simple ack, since client also has full comment data and can render it by itself.
这篇关于如何返回最后一个push()嵌入式文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!