Home>

We are currently creating a member management system.

-Problems occur
Although the connection from the control to the model is possible, we are faced with the problem of not being able to pass data from the model to the control.

-
I want to get data processed by the model from the control.

controller

var express = require ('express');
var router = express.Router ();
var user = require ('../ model/user');
// get database object
router.get ('/', function (req, res, nxet) {
    var data = user.listMember ();Called here
        res.render ('admin', data);
});
module.exports = router;

model

var sqlite3 = require ('sqlite3');
var db = new sqlite3.Database ('ChieproDB.sqlite3');
// member list
exports.listMember = () =>{
console.log ("Has been called");
    db.serialize (() =>{
        var query = `select * from member`;
            db.all (query, (err, rows) =>{
            if (! err) {
                return data = {
                title: 'Member List',
                member: rows,
                }
            }
        });
    });
}

It is connected to the model properly.

express-session deprecated undefined saveUninitialized option;provide saveUninitialized option app.js: 26: 9
undefined
POST/302 22.685 ms-54
Displayed in // console.log
GET/admin 500 12.563 ms-2069


**
Ideal image figure **

  • Answer # 1

    The story is different if you use it in Sails.js, but
    In the first place, MVC depends on the framework,
    Since the responsibilities of Koloro tend to change depending on the context, it is uncomfortable to say that it is MVC with homemade items.

    Also, I took a quick look at the code.
    There is an impression of the early code that is not well crafted.
    There are places where it is quite annoying whether this can be called a controller or model.

      

    tag: MySQL

    Where is MySQL?

    // Member List
    exports.listMember = () =>{
    console.log ("has been called");

    Make indentation.
    Other parts are messed up, so let's take measures by using a better editor.
    It can be a stress to other respondents who read the code, and the questioner's personality is also suspected.

      

    It is connected to the model properly.

    What did you connect with?
    Also, please do not skip "ra" in the text.


    It seems that there is not enough skill to write JavaScript as a major premise and realize your own MVC, so please use a ready framework such as Sails.js.

    If you still want to write your own, first learn how to write JavaScript asynchronously.
    Continue studying until you learn Promise and async/await.
    Your skills will not improve even if you ask questions repeatedly.

    Why don't you use classes for MVC?
    JS is originally prototype-based object-oriented, so if you can draw object-oriented with it, it's a different story ...
    Anyway, please learn and use the class syntax of ES2015.


    However, we decided that only the asynchronous concept should be shared.
    Please use it as a starting point.

    First, JavaScript runs on a single thread.
    A single thread cannot be waited at all, so reading and writing to a file or DB is much heavier than an instruction, so all other processing stops while waiting for them.
    Therefore, JavaScript adopted the concept of event loop.

    In JavaScript, we declare a lot of functions with a to-do list and a place to write things to do.
    We will hand over these functions so that they will be written as "Please execute this function when A is finished".
    Therefore, JavaScript functions can do almost the same as the numerical values ​​and character strings assigned to variables such as "Save to variable", "Set to argument", "Set to return value", etc.
    This is called a first-class object, but it is used as a means of transporting functions around.

    Anyone with a function can be executed by adding()to the bottom.
    All variables, arguments, and return values ​​will be executed if you add(),
    There is also an immediate execution function that is declared and executed immediately in parentheses, such as(function () {}) ().

    A function that has been written and handed over to another person can no longer retrieve the return value.
    It will be in the form of receiving the argument of the function that has been written.

    Based on that, let's improve the model in the question.

    db.serialize (() =>{
      var query = `select * from member`;
      db.all (query, (err, rows) =>{
        if (! err) return;
        return {
          title: 'Member List',
          member: rows,
        };
      });
    });

    This is an anonymous function as the first argument.
    In such a disposable process that does not need to be named, it is usually easier to create an anonymous function on the spot in this way and set it as an argument.

    Similarly, you can see thatdb.all (query, fn), and here also provides an intangible function as the second argument.
    The problem is thisreturn {}, and there is no recipient even if the storage (callback function) returns at this point, so it is not possible to retrieve this ddataIt will be possible.

    What do you do?
    It is necessary to prepare the writing on the Controller side and execute the strategy of extracting it by injecting it into the Model.

    Controller

    router.get ('/', (req, res, nxet) =>{
      user.listMember ((err, data) =>
        res.render ('admin', data)
      );
    });

    Model

    exports.listMember = (cb) =>{
      console.log ("Has been called");
      db.serialize (() =>{
        db.all (`select * from member`, (err, rows) =>{
          if (err) cb (err, null);return;
          cb (err, {
            title: 'Member List',
            member: rows,
          });
        });
      });
    };

    In this way,exports.listMemberhascbthat accepts the write function as an argument,
    Until thedb.allmethod ends, cb is carried around as a dummy argument, and after creating data, hit()at the bottom.

    If you want to fix it this way, you can fix it.
    However, it is a coping therapy, and if you ask questions in this way, you will surely have hundreds of questions to complete the system, so if you move to Sails.js (but this is also a minor frame) Since it is a work, it seems that there is nothing that can be relied only on Gachi English documents), but we recommend that you pay gently by crowdsourcing etc.