简体   繁体   中英

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

 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

 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

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

hope this helps :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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