如何在水线中通过(关联)模型添加模型(类)方法?

时间:2015-12-24 11:17:41

标签: javascript node.js sails.js waterline

给定一个带有字段的(关联)模型,我需要添加一些模型方法。

关联模型C

var BBPromise = require('bluebird');

module.exports = {

    attributes: {
        quantity: { type: 'integer' },
        //Relations
        a: { model: 'a', foreignKey: true, columnName: 'a_id' },
        workday: { model: 'b', type: 'date', foreignKey: true, columnName: 'b_id' }
    },
    //Instance method
    incrementQ: BBPromise.promisify(function (id, inc, cb) {
        C.findOne(id).then(function (found) {
            if (!found) {
                return cb({ status: 404, message: "didn't found the id" });
            }

            found.quantity += inc;
            console.log('AAAAAAAAAAAAA', found);
            return found.save(cb);
        }).catch(cb);
    })
};

当我尝试访问此方法时,我遇到了错误:c.incrementQ不是函数。

Test

var assert = require('chai').assert,
        destroyCollections = require('../../../helper').destroyCollections;

describe('C', function () {
    var idOfC;
    before(function (done) {
        B.create({ id: DateTimeService.generateNowDate() })
                .then(function (newB) {
                    A.create({ name: "my new a" }).then(function (newA) {
                        c.create({ a_id: newA.id, b_id: newB.id, quantity: 12 }).then(function (newC) {
                            idOfC = newC.id;
                            done();
                        }).catch(done);
                    }).catch(done);
                }).catch(done);
    });

    after(function (done) {
        destroyCollections(A, B, C, done);
    });

    it('incrementQ()', function (done) {
        console.log('THE MODEL', c);
        console.log('THE MODEL method', c.incrementQ);
        c.incrementQ(idOfC, -2).then(function (result) {
            assert.equal(result.quantity, 10, "quantity decremented");
            done();
        }).catch(done);
    });

});

为什么没有模型方法?

如何扩展关联模型?

P.S。这是github project with test

0 个答案:

没有答案