biggora / caminte

Cross-db ORM for NodeJS
http://www.camintejs.com/
MIT License
1.08k stars 119 forks source link

Problem with model assignment via relationship setter #119

Closed aayaresko closed 6 years ago

aayaresko commented 8 years ago

I have two models defined with repationships:

var date = Date.now() / 1000;
var Message = schema.define('message',
        {
            id: {
                type: schema.Number,
                unique: true
            },
            content: {
                type: schema.Text
            },
            author_id: {
                type: schema.Number,
                index: true
            },
            created_at: {
                type: schema.Date,
                default: date
            },
            updated_at: {
                type: schema.Date,
                default: date
            }
        },
        {
            primaryKeys: ['id']
        }
    );
var User = schema.define('user',
        {
            id: {
                type: schema.Number,
                unique:true
            },
            name: {
                type: schema.String,
                unique:true
            },
            email: {
                type: schema.String,
                unique:true
            },
            first_name: {
                type: schema.String
            },
            last_name: {
                type: schema.String
            }
        },
        {
            primaryKeys: ['id']
        }
    );
    User.prototype.getFullName = function() {
        var full_name = this.first_name + ' ' + this.last_name;
        if (full_name.trim()) {
            return this.email;
        }
        return full_name;
    };
User.hasMany(Message, {as: 'message', foreignKey: 'author_id'});
Message.belongsTo(User, {as: 'author', foreignKey: 'author_id'});

Assign author model to the message model:

User.findById(token.id, function( error, user ) {
            var message = new Message({content: 'demo'});
            message.author(user);
            message.save();
});

As a result the message.author_id should be equal to user.id, but in my case it results in that message.author_id contains an [Obejct]. AFAIK from debug information:

if (p instanceof AbstractClass) {
        this[fk] = p.id;
        this.__cachedRelations[methodName] = p;
...
} else { // setter
        this[fk] = p;
        delete this.__cachedRelations[methodName];
}

This condition always false because user model (and a message model btw) is not an instance of AbstratClass. Is this normal behavior or maybe I'm missing something here? Thanx in advance!