Karsten Morks
Karsten Morks

Reputation: 185

different models on one attribute in sailsjs

I'm currently setting up my models in a Sails.js application and was wondering if there was a possibility to solve my little problem nicely:

So I want to express the following relation:
A document has content, which is either of (model) type A or type B. Is there a way to express this without merging type A and B into one big model or adding one attribute for each type on the document model? Maybe something like enums for models and not for strings (if that's possible).

Or do I have to do the lookup via a unique ID like:

// model Document
module.exports = {

    contentType: {
        type: 'string',
        required: true,
        enum: ['typeA', 'typeB'],
    },
    contentID: {
       type: 'integer',
       required: true
    },
}

// model typeA
module.exports = {

    id: {
        type: 'integer',
        autoIncrement: true
    },
    heading: {
       type: 'string',
       required: true
    },
    body: {
       type: 'string',
       required: true
    },
}

Ideally I just want to write:

// model Document
module.exports = {

    contentType: {
        model: ['typeA', 'typeB'],
    },
}

or something like that (if that's possible).

Upvotes: 1

Views: 417

Answers (2)

galactocalypse
galactocalypse

Reputation: 1935

There is no way of doing that as of now, and the approach you're currently using is what I finally settled on after discarding the multiple-attribute approach(which works, but is very irritating to manage).

However, if your models (typeA and typeB) are light and you want to store them under the same attribute anyway, you could declare a custom validation as follows:

//model Document
function isTypeA(content) {
    //check if content is a valid typeA object
}
function isTypeB(content) {
    //check if content is a valid typeB object
}
module.exports = {
    types: {
        typeAOrTypeB: function(content){
            return isTypeA(content) || isTypeB(content);
        }
    },
    attributes: {
        contentType: {
            type: 'string',
            enum: ['typeA', 'typeB']
        },
        content: {
            type: 'json',
            typeAOrTypeB: true
        }
    }
}

(I would still prefer the multiple-model approach if content were even moderately detailed.)

Upvotes: 1

Andi N. Dirgantara
Andi N. Dirgantara

Reputation: 2051

AFAIK it can't be done without any application logic. Because SQL (also Sails/ Waterline relation) model is use table-to-table relation. Your relation, which is record-to-record are available in NoSQL graph db something like Neo4j, TitanDB, etc. and of course Waterline (currently) still not capable to integrate it.

Upvotes: 1

Related Questions