dresende / node-orm2

Object Relational Mapping
http://github.com/dresende/node-orm2
MIT License
3.07k stars 379 forks source link

key: true doesn't work on MongoDb #686

Open ghost opened 8 years ago

ghost commented 8 years ago

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 : 'admin@email.com', 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 ?

dxg commented 8 years ago

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

dresende commented 8 years ago

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

monatis commented 7 years ago

you can use orm.enforce.unique()

(...)

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

monatis commented 7 years ago

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(); }); }