5

I've the following model in my SailsJS application, I want to add composite unique key on the fields 'room_name' and 'school_id'.

What I currently do is run this command from mongo:

 db.room.ensureIndex({'room_name': 1, 'school_id':1}, {unique: true})

Question 1 Am I doing it right?

Question 2 Is it possible to modify my model so it automatically invokes this command without manually modifying the mongodb (from mongo command line)?

This is the model

module.exports = {

    schema: true,

    attributes: {

        room_name: {
            type: 'string',
            required: true
        },

        school_id: {
            type: 'string',
            required: true
        },

        children_count: {
            type: 'integer',
            required: true
        }
    }
   }
user2867106
  • 1,139
  • 1
  • 13
  • 31

4 Answers4

4

I created a sails hook to give advanced indexing options for models that use the sails-mongo adapter.

Supports all mongo indexing options.

https://www.npmjs.com/package/sails-hook-mongoat

Salakar
  • 6,016
  • 2
  • 18
  • 24
3

Sails does not currently (as of v0.10) support multi-key indexes, although it is on our radar. For the time being, the way you are doing it--by specifying the index directly in the Mongo console--is the correct (and only) way.

sgress454
  • 24,870
  • 4
  • 74
  • 92
  • any estimation to the release date of v0.10? I read the reference and cannot wait. Is it possible to download beta? and will it be a good idea? Thanks – user2867106 Apr 07 '14 at 07:15
  • You can install the Sails beta with `npm install sails@beta`. We are wrapping up documentation and hope to release soon. – sgress454 Apr 09 '14 at 05:01
1

Captain's log, stardate -303842.4081367327 (27th February 2019). Our destination is framework Sails 1.0x.

Even if Sails 1.0x/Waterline supports MongoDB composite indexes declaration in models (I'm not sure about that), when deploying your application in production, the indexes WILL NOT BE CREATED automatically... sad but true :(

Having that in mind...

Question 1 - Am I doing it right?

Yes you are... indexes are a bit complex and sometimes you will need to change them in production environment, so doing it by hand is necessary sometimes.

Question 2 - Creating indexes automatically

Yah... doing things by hand that could be done automagically is a pain in the donnuts...

For this issue, you can use the config/bootstrap.js file. Instead of ensureIndex function (it has been deprecated), you can use createIndex function (ensureIndex was an alias to createIndex). A working example of how to AUTOMATICALLY do that can be found here.

Dimas Crocco
  • 410
  • 6
  • 16
0

I am using migrations https://github.com/tj/node-migrate

for generating indexes

my code example

1nstinct
  • 1,745
  • 1
  • 26
  • 30