Skip to content

Instantly share code, notes, and snippets.

@chuck0523
Created September 19, 2016 06:01
Show Gist options
  • Save chuck0523/2939728be38450b3f9f5e967935df029 to your computer and use it in GitHub Desktop.
Save chuck0523/2939728be38450b3f9f5e967935df029 to your computer and use it in GitHub Desktop.
// By Calling thinky the connection pool will be created
const thinky = require('thinky')() // "Creating a pool connected to localhost:28015"
const type = thinky.type
// We can use reference to the RethinkDB driver
const r = thinky.r
r.now().run().then((time) => {
return time // 2016-09-19T05:22:53.098Z (example)
})
// Creating Model: thinky.createModel(tableName, schema, options)
const Post = thinky.createModel("Post", {
id: type.string(),
title: type.string(),
content: type.string(),
idAuthor: type.string()
})
const Author = thinky.createModel("Author", {
id: type.string(),
name: type.string()
})
// About valid schema read -> https://thinky.io/documentation/schemas/
// Join the models: belongsTo(OtherModel, fieldName, leftKey, rightKey[, options]))
Post.belongsTo(Author, "author", "idAuthor", "id")
// Creating new documents by instantiating Models
const post = new Post({
title: "Hello world",
content: "This is an example"
})
const author = new Author({
name: "Michel"
})
// Join the documents
post.author = author
// Save the document with joined ones. : SaveAll([modelToSave], [callback])
post.saveAll({author: true}).then((result) => {
//
})
// Foreign key will be automatically set
// Retrieve the Post with its author
Post.get('d2b2ee18-c8d2-45a0-9e89-35a7e026aea5')
.getJoin({author: true}).then((post) => {
// model {
// author: model { id: '97f5faed-4c7a-449c-8570-4aca9a273bf9', name: 'Michel' },
// content: 'This is an example',
// id: 'd2b2ee18-c8d2-45a0-9e89-35a7e026aea5',
// idAuthor: '97f5faed-4c7a-449c-8570-4aca9a273bf9',
// title: 'Hello world'
// }
// update author's name
post.author.name = 'John'
post.saveAll({author: true})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment