Using with JavaScript
TypeORM can be used not only with TypeScript, but also with JavaScript. Everything is the same, except you need to omit types and if your platform does not support ES6 classes then you need to define objects with all required metadata.
app.js
1
var typeorm = require("typeorm");
2
3
typeorm.createConnection({
4
type: "postgres",
5
host: "localhost",
6
port: 5432,
7
username: "test",
8
password: "admin",
9
database: "test",
10
synchronize: true,
11
entities: [
12
require("./entity/Post"),
13
require("./entity/Category")
14
]
15
}).then(function (connection) {
16
17
var category1 = {
18
name: "TypeScript"
19
};
20
var category2 = {
21
name: "Programming"
22
};
23
24
var post = {
25
title: "Control flow based type analysis",
26
text: "TypeScript 2.0 implements a control flow-based type analysis for local variables and parameters.",
27
categories: [
28
category1, category2
29
]
30
};
31
32
var postRepository = connection.getRepository("Post");
33
postRepository.save(post)
34
.then(function(savedPost) {
35
console.log("Post has been saved: ", savedPost);
36
console.log("Now lets load all posts: ");
37
38
return postRepository.find();
39
})
40
.then(function(allPosts) {
41
console.log("All posts: ", allPosts);
42
});
43
44
45
}).catch(function(error) {
46
console.log("Error: ", error);
47
});
Copied!
entity/Category.js
1
var EntitySchema = require("typeorm").EntitySchema;
2
3
module.exports = new EntitySchema({
4
name: "Category", // Will use table name `category` as default behaviour.
5
tableName: "categories", // Optional: Provide `tableName` property to override the default behaviour for table name.
6
columns: {
7
id: {
8
primary: true,
9
type: "int",
10
generated: true
11
},
12
name: {
13
type: "varchar"
14
}
15
}
16
});
Copied!
entity/Post.js
1
var EntitySchema = require("typeorm").EntitySchema;
2
3
module.exports = new EntitySchema({
4
name: "Post", // Will use table name `post` as default behaviour.
5
tableName: "posts", // Optional: Provide `tableName` property to override the default behaviour for table name.
6
columns: {
7
id: {
8
primary: true,
9
type: "int",
10
generated: true
11
},
12
title: {
13
type: "varchar"
14
},
15
text: {
16
type: "text"
17
}
18
},
19
relations: {
20
categories: {
21
target: "Category",
22
type: "many-to-many",
23
joinTable: true,
24
cascade: true
25
}
26
}
27
});
Copied!
You can checkout this example typeorm/javascript-example to learn more.
Copy link