简体   繁体   English

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

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

Hey guys i am pretty new to Nodejs so let me first describe my problem I created a mongooseschema of comments like 大家好,我对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);

then in my controllers file i created it and added it to db whenever user submits a comment 然后在我的控制器文件中,我创建了它,并在用户提交评论时将其添加到数据库中

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("/");
  });
};

now in later point of time when another user clicks on upvote button i want to increase the upvote entry in my db so i want to call a method in mongoose schema ..So i tried like this 现在在以后的时间点,当另一个用户单击upvote按钮时,我想增加数据库中的upvote条目,因此我想在猫鼬模式中调用方法。

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

and then in my schema 然后在我的架构中

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

}

but i get the error TypeError: Comments.upvoteco is not a function 但我收到错误TypeError: Comments.upvoteco is not a function

You can not call the method defined in schema with the model, You can call it with the object instance ie using and mongoose object instance(document) in that specific collection. 您不能使用模型调用在架构中定义的方法,而可以使用对象实例调用该方法,即在该特定集合中使用and mongoose对象实例(文档)。

And to call one with the model you should define a static method: 要使用模型调用它,您应该定义一个静态方法:

try changing: 尝试更改:

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

to this: 对此:

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

and try calling your method like: 并尝试像这样调用您的方法:

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

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

hope this helps :) 希望这可以帮助 :)

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

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