SailsJS and Mongo unique attribute is ignored
Asked Answered
C

3

5

I cant seem to get the unique attribute to actually check/validate for unique values while using Mongo in SailsJS. I end up with identical usernames easily. Any thoughts? I checked the other post about this, but that was related to using Disk/Memory databases.

Sails 0.10.x with [email protected]

Model:

module.exports = {

  attributes: {
    username:{
        type:'string',
        unique:true,
        required:true
    }
  }
};

Connections.js config file

mongo: {
    adapter: 'sails-mongo',
    host: 'localhost',
    port: 27017,
    schema:true,
    migrate: 'safe',
    database: 'mydatabase'
},
Combust answered 19/8, 2014 at 11:30 Comment(0)
E
8

Answered on GitHub here: https://github.com/balderdashy/sails-mongo/issues/181

When you have migrate: 'safe' set Waterline will not attempt to create any indexes on the database. Unique works by using the unique indexes created on the database during a "migration".

If you are in a production environment, you should create the indexes yourself and keep migrate: 'safe' set so that Waterline isn't touching your production data. In development you can set migrate: 'alter' and these indexes should be created.

Ender answered 19/8, 2014 at 16:15 Comment(2)
It seems that this option has now moved to models.js rather than connections.js.Denbrook
I've tried 'safe', 'alter' and 'drop' migrate values -- none worked for unique. How to force mongo to create indices?Burress
J
0

Have you tried:

  • Stop sails
  • Manually delete the relevant database + tables
  • Start sails
  • Try again

When you create a collection, the unique index is created at that point so if you're adding the unique attribute after you created the collection without it, it probably won't work. Using the mongodb driver directly will probably give you an error but since Waterline is agnostic, it probably doesn't care.

Juniper answered 19/8, 2014 at 14:50 Comment(0)
B
0

I've created a hook module that ensures indexes are created in all environments https://github.com/didil/sails-hook-mongo-auto-index . Hope it helps , suggestions are welcome

Blackguard answered 29/10, 2015 at 13:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.