Newcomer Newcomer - 21 days ago 6
Javascript Question

How to make POST work using router.post in Express JS

I'm very new to this and I'm following a tutorial.
Basically the app is about creating posts and comments to those posts.
I've created a POST for creating posts, but I can't get POST for comments to work. I have two models:

var Post = mongoose.model('Post');
var Comment = mongoose.model('Comment');


Posts model

var mongoose = require('mongoose');

var PostSchema = new mongoose.Schema({
title: String,
link: String,
upvotes: {
type: Number,
default: 0
},
comments: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'Comment'
}]
});

PostSchema.methods.upvote = function (cb) {
this.upvotes += 1;
this.save(cb);
};

mongoose.model('Post', PostSchema);


Comments model

var mongoose = require('mongoose');

var CommentSchema = new mongoose.Schema({
body: String,
author: String,
upvotes: {
type: Number,
default: 0
},
post: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Post'
}
});

mongoose.model('Comment', CommentSchema);


POST for posts that's working

router.post('/posts', function(req, res, next) {
var post = new Post(req.body);
post.save(function(err, post) {
if (err) {
return next(err);
}
res.json(post);
});
});


POST for comments that's not working

router.post('/posts/:post/comments', function(req, res, next) {
var comment = new Comment(req.body);
comment.post = req.post;

comment.save = function(err, comment) {
if (err) {
return next(err);
}
req.post.comments.push(comment);
req.post.save(function(err, post) {
if (err) {
return next(err);
}

res.json(comment);
});
};
});


And I'm using the following CURL for post creation (this one is working)

curl --data 'title=test12&link=http://test12.com&comments=bla' http://localhost:3000/posts


and this one for comments that's not working

curl --data 'something' http://localhost:3000/posts/58302f9662aa080ec9d75068/comments


The response to that call from server is:

POST /posts/58302f9662aa080ec9d75068/comments - - ms - -


Please help to resolve this issue.

Answer

There are a few issues:

comment.post = req.post

I think that you mean req.params.post here (refering to the :post placeholder in the URL pattern), not req.post.

comment.save = function(err, comment) { ... }

You probably want to call comment.save, not assign a new function to it:

comment.save(function(err, comment) { ... })