DAB
Search…
createCollection
1
createCollection(definition, param)
Copied!

Arguments

Definition (required)

Collection definition is a plain javascript object. In its simples form, it only needs a name:
  • name: a unique name to identify the collection. Required.
  • attributes: an object of column definitions. Optional.
Take a look at the example below:
1
{
2
name: 'users',
3
attributes: {
4
_id: 'string',
5
username: { type: 'string', length: 20, { validator: { required: true }}},
6
email: { type: 'string', length: 50, { validator: { required: true, isEmail: true }}},
7
fullname: { type: 'string', { validator: { required: true }}},
8
admin: { type: 'boolean', { validator: { required: true }}, default: false },
9
age: 'integer'
10
}
11
}
Copied!
Supported column types: string, integer, float, boolean, text, date, datetime.
If you put a text value instead an object in a column, it'll automatically be translated as its column type.
For some types like: integer, float, boolean, date, and datetime, it'll automatically put the right validator and sanitizer into account.
To hide some columns from result set, use hidden property and set it to true
To transform the key to something else, use mask property and set it to any key name.
Example:
1
...
2
// internally saved as this:
3
[
4
{ _id: 'james-bond', name: 'James Bond', gender: 'Male', age: 45 },
5
{ _id: 'jason-bourne', name: 'Jason Bourne', gender: 'Male', age: 36 },
6
...
7
]
8
...
9
// with this fields definition:
10
{
11
name: 'agents',
12
attributes: {
13
_id: { type: 'string', mask: 'code' },
14
name: { type: 'string', mask: 'fullName' },
15
gender: { type: 'string', mask: 'sex' },
16
age: { type: 'integer', hidden: true }
17
}
18
}
19
...
20
// and execute this method:
21
dab.find({ collection: 'agents' })
22
...
23
// will return this result set:
24
{
25
success: true,
26
data: [
27
{ code: 'james-bond', fullName: 'James Bond', sex: 'Male' },
28
{ code: 'jason-bourne', fullName: 'Jason Bourne', sex: 'Male' },
29
...
30
]
31
}
Copied!
You can also add column validators & sanitizers. These will guarantee that whatever you put in the database are in correct types and values.

Params (optional)

  • withSchema: optional, defaults to false. If set true, it'll destroy its internal database schema and rebuild a new one. In SQL database, this means very dangerous: drop existing table and recreate a new one with a schema built from the fields definition. All existing records & schema will be lost forever.

Response

Result

It should return an object like below:
1
{
2
success: true
3
}
Copied!

Error

It'll yield Collection already exists error if the collection name has been used before.
Any other error will yield a normal Node error object you can catch through promise easily.
Last modified 3yr ago