通过“ this”访问scheama方法中的属性

时间:2019-07-27 20:34:28

标签: javascript node.js mongoose

嘿,我只是想在Nodejs项目中使用猫鼬模式方法,所以在这里遇到了问题

在我的控制器文件中,我在db中提取了我的Comment的ID,然后 在注释模式文件中调用了一个方法,例如

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

  const id=req.params.id
  console.log(id)
  Comments.findById(id).then(c=>{
    console.log(c)
    Comments.upvoteco(c)
  })
  res.redirect('/')
}

,然后在我的注释模式文件中,我就拥有

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
  }

});
commentsschema.statics.upvoteco=function(c){

  console.log(c.upvote)
  console.log(this.firstname)
}

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

现在console.log(this.firstname)给我未定义的..为什么?即使我在数据库中输入

https://ibb.co/p0SdzYW

1 个答案:

答案 0 :(得分:0)

尝试做这样的事情:

const parent = commentsschema;
commentsschema.statics.upvoteco=function(c){

  console.log(c.upvote)
  console.log(parent.firstname)
}

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

如果您尝试在函数中使用this,则是指函数iteslf

相关问题