【问题标题】:TypeError: [function name] is not a function, in mongoose and node.jsTypeError: [function name] is not a function, in mongoose and node.js
【发布时间】:2016-02-13 10:21:57
【问题描述】:

我是 node.js 和 mongoose 的新手,如果有人能帮助我解决以下错误,我将不胜感激。

我通过以下函数提出了一个 put 请求(该函数的目的是“upvote”一个论坛帖子。

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

这反过来又去了我的路线:

index.js(我的路线)

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

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

下面是我的模型

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

在我的 index.js 路由中,“req.post.upvote”行引发了以下错误:

TypeError: req.post.upvote 不是函数

【问题讨论】:

  • req.post 应该是什么?

标签: javascript node.js mongodb mongoose


【解决方案1】:

req.post 不会自动设置。您需要另一个中间件来设置它,但很可能您想通过参数从数据库中获取它。

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

编辑:您还需要在 mongoose 中创建模式之前设置方法

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

mongoose.model('Post', PostSchema);

【讨论】:

  • 我已经在我的代码前面定义了一个名为“post”的参数,(对不起,我没有在我的原始帖子中包含它)。但是当我调试时,我能够正确地看到“post”对象。问题是我想调用模型中定义的“upvote”函数,但我似乎做不到。谢谢
  • @Flame1845 可以尝试移动mongoose.schema 调用之后你设置.methods
  • 你的传奇,修复它...非常感谢!我不知道我必须这样做......我会记住它的未来!
猜你喜欢
  • 1970-01-01
  • 2013-12-22
  • 2020-01-18
  • 2017-04-13
  • 1970-01-01
  • 2021-11-12
  • 2015-09-18
  • 2020-03-17
  • 2020-01-06
相关资源
最近更新 更多