node-orm2 icon indicating copy to clipboard operation
node-orm2 copied to clipboard

key: true doesn't work on MongoDb

Open ghost opened this issue 9 years ago • 4 comments

Hi everyone,

var Account = db.define('account', { email : { type: 'text', key: true }, password : String, lastname : String, firstname : String, superAdmin : Boolean }, { timestamp : true, validations : { email : [orm.enforce.required(), orm.enforce.notEmptyString(), orm.enforce.patterns.email()], password : [orm.enforce.required(), orm.enforce.notEmptyString(), orm.enforce.security.password()], lastname : [orm.enforce.required(), orm.enforce.notEmptyString()], firstname : [orm.enforce.required(), orm.enforce.notEmptyString()] } });

And when I create

Account.create({ email : '[email protected]', password : 'aB123-', lastname : 'None', firstname : 'Administrator', superAdmin : true }, function (err, account) { if (err) throw err; });

When I check in mongodb db.account.find({}) I have an _id column and after many execution of the Account.create I have many accounts with same email

Any idea ?

ghost avatar Dec 11 '15 08:12 ghost

I don't know about mongo as I don't use it. Perhaps ask @dresende

dxg avatar Dec 14 '15 01:12 dxg

I haven't used mongodb for a long time. This key: true thing was brought later to the lib (and I'm glad it is in) but mongodb part was not upgraded.

It should be something around this function, I have no time to check it now.

https://github.com/dresende/node-orm2/blob/master/lib/Drivers/DML/mongodb.js#L24

dresende avatar Dec 14 '15 09:12 dresende

you can use orm.enforce.unique()

(...)

  email : [orm.enforce.required(), orm.enforce.notEmptyString(), orm.enforce.patterns.email(), orm.enforce.unique()],  (...)

monatis avatar Dec 30 '16 14:12 monatis

It seems that orm.enforce.unique() does not work for mongodb, either. Instead, I hookked to beforeCreate as in the following: beforeCreate: function(next) { db.models.user.exists({email: this.email}, (err, exists) => { if(exists) return next(new Error('email_already_registered')); this.regDate = new Date(); return next(); }); }

monatis avatar Dec 31 '16 11:12 monatis