0

I have a case where I need to change the default referencing of primary key name id with _id for all the models in a given project I am working.

There is an express.js + mongoose setup which is in production. The data present in the database is directly referred by our users using mobile application. And the code of mobile application is very much aware of reading _id as the key in all the documents it receives in JSON.

Since sails uses waterline which has default key name as id and it maps to _id for mongodb, the underlying database will be used as it is, however on the middleware we are always reading it as id.

I have searched through the web and tried to have default id name as _id in the config/models.js, but the schema creation outputs an error stating _id, _id is used twice.

  • you dont need to change id to _id everywhere. Just model configuration. In other places just use 'id' with type string. – Vikas Kumar Sep 26 '19 at 05:16
  • Hi, thanks ! But... it does not solve my problem because my mobile apps are educated to understand _id. The model we use in sailsjs has id as the name, the json contains id as the key and not _id. – Naval Patel Sep 26 '19 at 14:31

1 Answers1

0

Production database, Waterline ... I recommend against actually changing your primary keys. Heck, I'd recommend against that kind of monkey-wrench if you were using a much more mature ORM.

Instead, I say, transform the key names in your action. e.g. in an action2, where you just return template variables at the end of a function:

  r = await Model.findOne(where);
  return {
    _id: r.id,  // <---- this bit <----
    etc: r.etc
  }

And then make a JSON structure as your view template.

Nathan Hawks
  • 557
  • 4
  • 14