How to return the last push() embedded document
-
26-10-2019 - |
题
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();
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' });
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.