簡體   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