W
W
Wasya UK2018-07-11 12:37:05
JavaScript
Wasya UK, 2018-07-11 12:37:05

How to pass Mongoose model?

I'm trying to make a common controller for models and add new features for each, but I get several errors, and I don't understand what I'm doing wrong.

I checked how a normal model should look like, but when I pass it through the constructor, something else turns out:

Controller constructor function model(doc, fields, skipId) {
      model.hooks.execPreSync('createModel', doc);
      if (!(this instanceof model)) {
        return new model(doc, fields, skipId);
      }
      Model.call(this, doc, fields, skipId);
    }


When I check ID I get another error:
TypeError: Project.checkId is not a function

Code example:
const mongoose = require('mongoose');
const ProjectModel = require('../models/project');

class Controller {
  constructor(model) {
    console.log("Controller constructor", model); // ТУТ НЕ МОДЕЛЬ, А Controller constructor function model
    if (!model || !model.collection.name) {
      throw new Error(404, "Controller need mongoose model in constructor!");
    }
    this.name = model.collection.name;
    this.model = model;
  }

  static checkId(id) {
    return mongoose.Types.ObjectId.isValid(id.toString());
  }
}

class ProjectController extends Controller {
  constructor(name, model) {
    super(model)
    this.name = name;
  }

  static create(fields) {
    this.checkFields(fields);

    const newProject = new ProjectModel({
      name: fields.name,
      description: fields.description,
      slides: []
    });

    return newProject.save();
  }
}

module.exports = Project = new ProjectController('Project', ProjectModel);

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question