JavaEvgen JavaEvgen - 1 month ago 10
Node.js Question

How to get an _id of parent document mongoose

I'm trying to implement a method in express router, that would delete an embedded document from a parent document by its

_id
.

My code looks like this:

.hbs

<table class="table table-striped table-bordered">
<tr>
<th>Title</th>
<th>Description</th>
</tr>
<tr>
<td>{{movie.title}}</td>
<td>{{movie.genre}}</td>
</tr>
</table>
<br>
<table class="table table-striped table-bordered">
<tr>
<th>Author</th>
<th>Comment</th>
<th>Action</th>
</tr>
{{# each movie.comments}}
<tr>
<td>{{this.author}}</td>
<td>{{this.comment}}</td>
<td><a href="comment/delete/{{movie._id}}/{{this._id}}">Delete</a></td>
</tr>
{{/each}}
</table>


I can easily get an _id of my embedded doc (single comment), but I can't get an _id of my parent (movie) doc.

On back-end everything seems to be ok, but I get 404 error, because movie._id is empty so my
link(/movie/comment/delete//58111f46d7cf8730305e1d5c)
doesn't match its pattern in router.

I populate my view with this:

Movie.findById(req.params.id).populate('comments').exec(function(err, movie)


and render the movie object

Answer

Since the context changes in #each, try going up a level:

<a href="comment/delete/{{../movie._id}}/{{this._id}}">Delete</a>
Comments