嘿,我只是想在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)给我未定义的..为什么?即使我在数据库中输入
答案 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