forked from Atlantis-Software/offshore-docs
-
Notifications
You must be signed in to change notification settings - Fork 2
/
getting-started.js
102 lines (89 loc) · 2.03 KB
/
getting-started.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
/**
* A really simple Offshore application.
*
* @license MIT
*/
var Offshore = require('offshore');
var MemoryAdapter = require('offshore-memory');
// Create the offshore instance.
var offshore = new Offshore();
// Create a specification for a User model.
var userCollection = Offshore.Collection.extend({
identity: 'user',
connection: 'default',
attributes: {
firstName: 'string',
lastName: 'string',
// Add a reference to Pets
pets: {
collection: 'pet',
via: 'owner'
}
}
});
// Create a specification for a Pet model.
var petCollection = Offshore.Collection.extend({
identity: 'pet',
connection: 'default',
attributes: {
breed: 'string',
type: 'string',
name: 'string',
// Add a reference to User
owner: {
model: 'user'
}
}
});
// Add the models to the offshore instance.
offshore.loadCollection(userCollection);
offshore.loadCollection(petCollection);
// Set up the storage configuration for offshore.
var config = {
adapters: {
'memory': MemoryAdapter
},
connections: {
default: {
adapter: 'memory'
}
}
};
// Initialise the offshore instance.
offshore.initialize(config, function (err, ontology) {
if (err) {
return console.error(err);
}
// Tease out fully initialised models.
var User = ontology.collections.user;
var Pet = ontology.collections.pet;
// First we create a user.
User.create({
firstName: 'Neil',
lastName: 'Armstrong'
})
.then(function (user) {
// Then we can create a pet for the user.
// Note that offshore automatically adds the `id` primary key to the model.
Pet.create({
breed: 'beagle',
type: 'dog',
name: 'Astro',
owner: user.id
})
.then(function (pet) {
// Then we can associate the pet with the user.
user.pets = [pet];
// And save the user.
return user.save();
})
.then(function () {
// And now we want to get the new user back,
// and populate the pets the user might own.
return User.find()
.populate('pets');
})
.then(console.log)
.catch(console.error);
});
});