javascript - How to make POST work using router.post in Express JS -
i'm new , i'm following tutorial. app creating posts , comments posts. i've created post creating posts, can't post comments work. have 2 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 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 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 following curl post creation (this 1 working)
curl --data 'title=test12&link=http://test12.com&comments=bla' http://localhost:3000/posts and 1 comments that's not working
curl --data 'something' http://localhost:3000/posts/58302f9662aa080ec9d75068/comments the response call server is:
post /posts/58302f9662aa080ec9d75068/comments - - ms - - please resolve issue.
there few issues:
comment.post = req.post i think mean req.params.post here (refering :post placeholder in url pattern), not req.post.
comment.save = function(err, comment) { ... } you want call comment.save, not assign new function it:
comment.save(function(err, comment) { ... })
Nice post! This is a very nice blog that I will definitively come back to more times this year! Thanks for informative post.
ReplyDeletedefer parsing of js wordpress