scottwrobinson / camo

A class-based ES6 ODM for Mongo-like databases.
556 stars 80 forks source link

Dynamic key support #90

Open Benabra opened 7 years ago

Benabra commented 7 years ago

Hi,

Thank your for this great project. I have just one functional question, I have a dynamic key like :

{
_id: ObjectId('oNe1D')
certifications: [{
 $userId: {
     'certified': true,
     'level': 5
 }]
}

$userId is a dynamic key, so i cant define it on my model schema. I dont know if we can do this with camo our we need to implement it manualy ?

Thank's

perimetral commented 7 years ago

Try to use syntax for computable keys:

let w = 'qq';
let r = {
  x: 1,
  [w + 'ee']: 2
};
console.log(r);  //  result will be "{ x: 1, qqee: 2 }"

I'm not sure this will work correctly in Camo schema definition, but as long as class constructors work synchronously, this must work.

Anyway i don't see schema definitions in your example. It has two syntax errors: no comma after second line and missing of closing brace at seventh one. But this isn't main: you are asking about schema providing instance.

If you have some field defined as Object inside your schema, there will not be any issues with using of computable keys in it, considering there are no documents with fields referenced to computable key until key is computed and persistently saved.

You are free to do this way (will insert initial data but not more, as long as $userId is variable and is computed only once to determine key to use, so any next inserts will fail with "key exists" error):

certifications: [{
  [$userId]: {  //  notice change
    certified: true,
    level: 5
  }
}];

Also you are free to do this way (best way):

certifications: [{
  user: $userId,
  certified: true,
  level: 5
}];

Or this way:

certifications: {  //  notice change again
  [$userId]: {
    certified: true,
    level: 5
  },
  //  [$userId2]: ...
};
Benabra commented 5 years ago

/close