Search code examples
javascriptrethinkdbthinky

How to create a new n-n model using thinky and link it to an existing one?


I just started using rethinkDB and thinky. I wanted to ask how I go about creating a new instance of a model which has n-n relationship with an already existing model. For example, if I have a model for Pizzas and Toppings. I already created a Pizza instance, how do I create a topping instance and link it to the already existing pizza?

var Pizza = thinky.createModel("Pizza", {
    name: type.string(),
    size: type.string()

});
var Topping = thinky.createModel("Topping", {
    name: type.string(),

});

Pizza.hasAndBelongsToMany(Topping, "toppings", "id", "id");
Topping.hasAndBelongsToMany(Pizza, "pizzas", "id", "id");

var pizza = new Pizza({name:"My pizza", size:"Large"});
var topping = new Topping({name:"Olive"});

How do I go about saving a topping so it would relate to the already created pizza?

In the docs, for 1 - n relations they do something like:

topping.pizzas = pizza
topping.saveAll({pizza: true}).then(...);

In this case, it won't work because topping.pizzas is an array of objects and not just a single object.


Solution

  • The answer is pretty simple I found out:

    var pizza = new Pizza({name:"My pizza", size:"Large"});
    var topping = new Topping({name:"Olive"});
    
    Topping.filter({name:Olive}).run().then(function (topping) {
        if (topping.length > 0){
            if (pizza.toppings == undefined){
                pizza.toppings = []
            }
        pizza.toppings.push(topping[0]);
        pizza.saveAll().then(...)
        }
    }
    

    Pretty sure there are better ways to do it, but this works.