PhilWaldmann / openrecord

Make ORMs great again!
https://openrecord.js.org
MIT License
486 stars 38 forks source link

create(data) but get null #95

Closed ryougifujino closed 5 years ago

ryougifujino commented 5 years ago
const Store = require('openrecord/store/sqlite3');
const store = new Store({
    type: 'sqlite3',
    file: __dirname + '/rf-blog.db',
    autoLoad: true,
});

class Album extends Store.BaseModel {
    static definition() {
        this.attribute('id', 'integer', {primary: true});
        this.attribute('name', 'string');
        this.attribute('created_on', 'datetime');
    }
}

store.Model(Album);

async function openDB() {
    await store.connect();
    await store.ready();
    console.log('connected');
}

async function operateDB() {
    try {
        const album = await Album.create({
            name: 'Jack',
            created_on: new Date()
        });
        console.log(album)
    }catch (e) {
        console.log(e);
    }
}

async function closeDB() {
    await store.close();
    console.log('closed');
}

async function main() {
    await openDB();
    await operateDB();
    await closeDB();
}

main();

When I executed this script, I got result on the console:

connected
  <Album {id:5 name:"Jack" created_on:"2019-03-20T01:46:16.944Z"}>
closed

But I got null in database. sampel

And after I commented the two lines:

//        this.attribute('name', 'string');
//        this.attribute('created_on', 'datetime');

The result seems perfect: sample2

But why?

PhilWaldmann commented 5 years ago

openrecord will load the available fields from your table automatically. If you overwrite them via this.attribute() they wont be synced to the database anymore (except you specify the writable option.

So in your example. just remove the static definition() method of your model and everything should be fine.

btw: store.ready() will call store.connect() unless you set the store autoConnect option to false.

ryougifujino commented 5 years ago

thanks for replying