I have a Post
model and a Comment
model. When a user posts a comment, the postID
will be sent as a param.
Once the comment is saved, it's id
will be pushed into the comments
array that belongs to the post.
The Post
model has a commentCount
which is a virtual property, which will count how many comment IDs are in the comments
array.
This is my commentController:
create(req, res, next) {
const commentProps = req.body;
const postId = req.params.id;
Comment.create(commentProps)
.then(comment => {
Post.findById({ _id: postId })
.then(post => {
console.log(post);
console.log('comment id is ' + comment._id);
post.comments.push(comment._id);
console.log(post);
console.log('commentCount is ' + post.commentCount);
});
return res.send(comment);
})
.catch(next);
},
All the logs are coming through just as they should be. The comment._id
gets pushed right into the comments
array and the commentCount
has been incremented by 1
.
Yet my test assertion is not passing:
it('POST to /api/comments/:id creates a new comment and increases posts commentCount', done => {
const post = new Post({
author: user._id,
text: 'This is a post',
createdAt: 0,
expiresAt: 0,
voteCount: 0
});
post.save()
.then(() => {
Comment.count().then(count => {
request(app)
.post(`/api/comments/${post._id}`)
.send({
author: user._id,
text: 'This is a comment',
createdAt: 0,
postId: 'randomPost'
})
.end(() => {
Comment.count().then(newCount => {
console.log('Comment count is ' + post.commentCount);
assert(count + 1 === newCount);
assert(post.commentCount === 1);
done();
});
});
});
});
});
The log in the test above comes back as 0
and if I log the post.comments
then it just comes back as an empty array.
Any idea what I'm doing wrong here guys?
Thanks!