huiguang1
huiguang1

Reputation: 41

How to get create() return auto-increment primary key after creation in sails.js?

I have a model, Case.js:

...
attributes: {
    id: {
        type: 'integer',
        unique: true,
        primaryKey: true,
        columnName: 'pid' //an auto-increment primary key, generated by MySQL
    },
    ...
}

And I want to get this id after creation:

Case.create({...}).then(function(aCase){
    console.log(aCase.id);
})

The creation succeeded, but the output I got is undefined. I tried setting autoPK to false, and deleting "unique" and "primaryKey" entry, but the result didn't change. Please tell me how to make create() return this id.

Upvotes: 2

Views: 931

Answers (2)

huiguang1
huiguang1

Reputation: 41

I've worked it out myself. The problem lies in my model Case.js. In sails.js, if you want a primary key (usually id) created by MySQL with auto-increment to be returned after create(), your model should look like this:

module.exports = {
    ...
    autoPK: false,
    attributes: {
        id: {
            type: 'integer',
            unique: true,
            primaryKey: true,
            autoIncrement: true,
        },
        ...
    }
}

Pay attention to "autoIncrement" attribute, it is necessary in my case, and probably in every auto-increment primary key.

Upvotes: 2

Royalist
Royalist

Reputation: 71

I'm looking at the Sails.js documentation for creating a new entry in a database. The method is indicated as

Something.create(values).exec(function (err, records) {

});

In your case, you should have

Case.create({...}).exec(function(err, aCase){
    console.log(aCase.id);
})

Upvotes: 0

Related Questions