Search code examples
node.jsmongodbsails.jswaterlinesails-mongo

SailsJS: Setting autoPK:false still generates mongodb's id attribute


Using SailsJS, I'm trying to figure out how to use a custom Primary Key as Integer that auto increments.

For that, I passed autoPK:false, but I see that mongo still used it's 'id' field with UUID, as if Waterline is ignoring my autoPK entry.

For example, I define this model (configured for mongodb)

module.exports = {
  autoPK: false,
  attributes: {
    name:'string',
    personalId: {
      type: 'integer',
      autoIncrement:true,
      primaryKey: true
    }
  }
}

Here's an output from sails console:

sails> User.create({name:'Mike'}).exec(console.log)
undefined
sails> null { name: 'Mike',
  createdAt: Fri Mar 27 2015 22:11:51 GMT+0300 (IDT),
  updatedAt: Fri Mar 27 2015 22:11:51 GMT+0300 (IDT),
  id: '5515ab77ac1085260b221cfd' }

I would expect to see personalId:1 or something like that instead of id:'5515ab77ac1085260b221cfd'.

Thanks.


Solution

    1. Mongo's auto increment in Sails can't be sequentially 1, 2, 3, etc. It will always be Mongo's ObjectId.
    2. id field in Sails is necessary, since many convention still use it. Look after blueprint actions, actionUtil, etc.

    So here is my solution, use this model configuration:

    module.exports = {
      autoPK: false,
      attributes: {
        name:'string',
        id: {,
          autoIncrement:true,
          primaryKey: true,
          columnName: 'personalId'
        }
      }
    }
    

    It still not generate personalId as column name in Mongo, but it will use Mongo's default id convention which is _id. personalId will be generated if you switch your DB to another one like MySQL.