在node / express中向knex / bookshelf模型添加功能

时间:2018-11-05 17:46:16

标签: node.js express knex.js bookshelf.js

我有一个这样的模型:

const User = db.Model.extend({
    tableName: 'users',
    hasSecurePassword: true
});

module.exports = User;

有了这个我就可以做

const User      = require("../models/user");

 User.fetchAll({columns:['id','email']}).then((data) => {
        res.json(data);
    }).catch(err => {
        res.json(err);
    });

如果我想在模型中添加服装功能怎么办?

var connection  = require('./dbconnection.js');
var User = db.Model.extend({
    tableName: 'users',
    hasSecurePassword: true
});


User.getUsers = (callback) => {
    if (connection) {
        const newLocal = "select * FROM users";
        connection.query(newLocal, (err,rows,fields) => {
            if (err) {
                return res.sendStatus(500);
            } else {
                callback(null,rows);
            }
        });
    }
};

module.exports = User;

然后执行以下操作:

 const User      = require("../models/user");
 User.getUsers((err,data) => {
    res.status(200).json(data);
});

这是可能的吗?还是应该只符合书架功能? 现在我得到的错误是connection.query is not a function

models / dbconnection.js是:

const mysql = require('mysql');
port = process.env.PORT || 3333;


if (port == 3333) {
    var connection = mysql.createConnection({
        host: process.env.DB_HOST,
        port: process.env.DB_PORT,
        user: process.env.DB_USER,
        password: process.env.DB_PASSWORD,
        database: process.env.DB_NAME,
        insecureAuth: true
    });
} else {
    console.log("Error");
}

connection.connect();
module.exports.connection = connection;

1 个答案:

答案 0 :(得分:1)

是的,您可以通过两种不同的方式将自定义函数添加到书架模型中。

  1. 实例方法

例如,您要返回用户的全名,您的用户模型将如下所示

const User = db.Model.extend({
    tableName: 'users',
    hasSecurePassword: true,

    //be careful here, if you use arrow function `this` context will change 
    //and your function won't work as expected

    returnFullName: function() {
       return this.get('firstname') + this.get('lastname');
    }
});

module.exports = User;

然后您将像这样调用此函数

User.forge().where({id: SOME_ID}).fetch()
    .then(function(user) {
        var fullName = user.returnFullName();
    });
  1. 类方法

例如,您要根据用户名返回用户的电子邮件,您的用户模型将如下所示

const User = db.Model.extend({
    tableName: 'users',
    hasSecurePassword: true
}, {

    getUserEmail: function(SOME_USERNAME) {
        return User.forge().where({username: SOME_USERNAME}).fetch()
            .then(function (user) {
                if(user) {
                    return Promise.resolve(user.get('email'));
                } else {
                    return Promise.resolve(null);
                }
            });
    }        
});

module.exports = User;

然后您可以像

一样调用此函数
User.getUserEmail(SOME_USERNAME)
    .then(function(email) {
        console.log(email);
    });