这不是指猫鼬模式

时间:2020-04-14 09:43:53

标签: node.js express mongoose mongoose-schema

我有猫鼬模式,那就是代码

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var projectsSchema = new Schema({
    title : {
        type: String,
        required : true
    },
    description : {
        type: String,
        required : true
    },
    mainimg_path : {
        type: String,
        required : true
    }
});

module.exports = projectsSchema;

并在dao模块中进行数据库查询,这就是代码

var mongoose = require('mongoose');
var projectsSchema = require('./projects.model');

projectsSchema.statics = {
    createProject : async (data) => {
        try{
            console.log(this)
            const addedProject = await new this(data);
            await addedProject.save();
        }
        catch(e){
            console.log("error occured while saving a new project")
            console.log(e)
        }  
    },

    get : async () => {
       try{
           console.log(projectsSchema)
           await this.find({});
       }
       catch(e){
        console.log("error occured while retreive a new project")
        console.log(e)
       }
   }
}

var projectsModel = mongoose.model('Projects', projectsSchema);
module.exports = projectsModel;

最后是控制器模块

var Projects = require('./projects.dao');
const { check, validationResult } = require('express-validator');

exports.validate = (method) =>{
    switch(method){
      case "createProject":
          return [
            check("title", "title is required")
            .not()
            .isEmpty().withMessage("tile must not be empty")
            .isLength({ min: 2,max:100 }).withMessage("title long min is : 2 chars max is : 100 chars"),
            check("description", "description is required")
            .not()
            .isEmpty().withMessage("description must not be empty")
            .isLength({ min: 2,max:3000 }).withMessage("title long min is : 2 chars max is : 3000 chars")
            ]     
      default:
    }   
}


exports.createProject = async  (req, res, next)=>{
    try{
       const errors = validationResult(req); 
        if (!errors.isEmpty()) {
        res.status(422).json({ msg:"validationErr", errors: errors.array() });
        return;
       }
       if(!req.file){
           res.status(422).json({msg:"you must select img"});
           return
       }
        const project = {
        title: req.body.title,
        description: req.body.description,
        mainimg_path: req.file.filename
             }
        await Projects.createProject(project);
        res.status(200).json({msg:"new project added successfully",hexCode:"00"})
    }
    catch(e){
        console.log(e);
        res.status(400).json({msg:"err occurred while adding a new project",hexCode:"FF"})
    }
}


exports.getAllProjects = async (req, res, next)=>{
    try{
       const projects = await Projects.get();
       res.status(400).json({msg:"all projects retreived successfully",hexCode:"00",projects:projects})

    }
    catch(e){
        console.log(e);
        res.status(400).json({msg:"error occurred while trying retreive all projects",hexCode:"FF"})
    }
}

当我尝试发布新项目时发生错误(这不是构造函数) 当我尝试获取所有项目时,发生了错误(this.find不是函数);

为什么会发生这种错误?预先感谢

2 个答案:

答案 0 :(得分:0)

我认为this的范围将是包装方法的对象。

尝试按照docs

中的指示使用静态变量
    projectsSchema.statics.createProject = async function (data) {
        try{
            console.log(this)
            const addedProject = await new this(data);
            await addedProject.save();
        }
        catch(e){
            console.log("error occured while saving a new project")
            console.log(e)
        }  
    };

    projectsSchema.statics.get = async function () {
       try{
           console.log(projectsSchema)
           await this.find({});
       }
       catch(e){
        console.log("error occured while retreive a new project")
        console.log(e)
       }
   }

答案 1 :(得分:0)

我解决了这个问题,我使用普通的function关键字而不是arrow function,所以现在指向对象而不是该函数

相关问题