大家好,我是Nodejs的新手,让我先描述一下我的问题
我创建了评论的猫鼬模式

 const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const commentsschema = new Schema({
  firstname: {
    type: String,
    required: true
  },
  middlename:{
    type:String
  },
  lastname:{
    type:String,
    required:true
  },
  comments:{
      type:String,
      required:true
  },
  upvote:{
      type:Number
  },
  downvote:{
      type:Number
  }

});
module.exports = mongoose.model("comments", commentsschema);


然后在我的控制器文件中,我创建了它,并在用户提交评论时将其添加到数据库中

exports.postcomment = (req, res, next) => {

  //All firstname, lastname etc are taken from req.body just to make my code short i havent included those lines

  const commentinpage = new Comments({
    firstname: fname,
    middlename:mname,
    lastname:lname,
    comments: comment,
    upvote: 0,
    downvote: 0
  });
  return commentinpage.save().then(() => {
    res.redirect("/");
  });
};


现在在以后的时间点,当另一个用户单击upvote按钮时,我想增加数据库中的upvote条目,因此我想在猫鼬模式中调用方法。

 const Comments = require("../modals/Comments");
 Comments.upvoteco().then(result=>{
 console.log(this.upvote)
 }


然后在我的架构中

commentsschema.methods.upvoteco=function(){
  console.log(this.upvote)
return  ++this.upvote

}


但我收到错误TypeError: Comments.upvoteco is not a function

最佳答案

您不能使用模型调用在架构中定义的方法,而可以使用对象实例(即在特定集合中使用和猫鼬对象实例(文档))调用该方法。

要使用模型调用它,您应该定义一个静态方法:

尝试更改:

commentsschema.methods.upvoteco = function() {
  console.log(this.upvote);
  return ++this.upvote;
}


对此:

commentsschema.statics.upvoteco = function() {
  console.log(this.upvote);
  return ++this.upvote;
}


并尝试像这样调用您的方法:

Comments.upvoteco(function(err, result) {
    if (err) {
        console.log('error: ', err);
    } else {
        console.log(this.upvote);
    }
});


检查官方文档以了解更多信息:https://mongoosejs.com/docs/2.7.x/docs/methods-statics.html

希望这可以帮助 :)

07-24 09:51
查看更多