繁体   English   中英

从控制器到猫鼬模式文件(Nodejs)的调用方法

[英]Calling methods from controllers to mongoose schema file (Nodejs)

大家好,我对Node.js很陌生,所以让我首先描述一下我的问题,我创建了一个mongooseschema,例如

 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

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

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

尝试更改:

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

希望这可以帮助 :)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM