2

I'm new to node.js and mongoose, and I'd appreciate it if someone could help me with the below error.

I make a put request via the following function (the point of the function is to "upvote" a forum post.

o.upvote = function(post) {
    return $http.put('/posts/' + post._id + '/upvote')
        .success(function(data){
            post.upvotes += 1;
        });
};

That in turn goes to my route:

index.js (my route)

router.put('/posts/:post/upvote', function(req, res, next) {
    req.post.upvote(function(err, post){
        if (err) { return next(err); }

        res.json(post);
    });
});

And below is my model

Posts.js

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' }]
});

mongoose.model('Post', PostSchema);

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

In my index.js route, the below error is thrown on the line "req.post.upvote":

TypeError: req.post.upvote is not a function

1
  • What is req.post supposed to be? Commented Feb 13, 2016 at 1:59

1 Answer 1

2

req.post will not be set automatically. You need another middleware to set it, but most likely you want to get it from the DB with the parameter.

const Post = mongoose.model("Post");

router.put("/posts/:post/upvote", (req, res, next) => {
  Post.findById(req.params.post, (err, post) => {
    if (err) return next(err);
    post.upvote((err, post) => {
      if (err) return next(err);
      res.json(post);
    });
  });
});

EDIT: You also need to set the methods before you create the schema in mongoose:

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

mongoose.model('Post', PostSchema);
Sign up to request clarification or add additional context in comments.

3 Comments

I already have define a parameter earlier in my code called "post", (sorry I didn't include it in my original post). But when I debug, I am able to see the "post" object correctly. The issue is that I want to call the "upvote" function defined in my model, but I can't seem to do that. Thanks
@Flame1845 maybe try moving the mongoose.schema call after the you set the .methods
you legend, that fixed it...thanks a lot! I wasn't aware that I had to do that...I'll keep it in mind for the future!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.