Sequelize, save an object along with a child (related) object

I created my models to continue. I have a User model that is attached as an Address object. Links are defined as such:

User.hasMany(Address);

Address.belongsTo(User);

      

The object I'm trying to save has the correct structure with the child attached:

{
      Username: "John",
      Email: "John@test.com",
      Address: [{
          street: "somestreet"
      }]
  };

      

When I try to create an object, the parent is inserted into my database, but the application exits with the [sequelize] object, does not contain a .save () method

I am creating the following:

User.create(user).success(function(user){

});

      

I have registration enabled on my sequelize instance and I can see the correct parent is being created, but I am stuck on how to properly store the child (linked) object.

+3


source to share


3 answers


It turns out that Wrikken's original comment was correct, I was passing in a single object, not an array.

This fixed it:



 {
      Username: "John",
      Email: "John@test.com",
      Address: [{
          street: "somestreet"
      }]
  };

      

+1


source


I don't think you can create a linked object like this.

Other things: you shouldn't use a success handler anymore. User .then

, .catch

and .finally

.

I am assuming you have a primary key userId

for your model User

. Else, replace userId

in the example below with your primary key, which might be Username

.

You should:



var user = {
    Username: "John",
    Email: "John@test.com"
};

User.create(user).then(function(user) {
    // sequelize passes the newly created object into the callback,
    // and we named the argument "user".
    // "user" is now a sequelize instance that has the association
    // methods of add[AS]. So we use it.

    var address = Address.build({
        street: "somestreet"
    };
    return user.addAddress(address);
}).then(function(address){
    //do something with address?
}).catch(function(err){
    //do something with your err?
});

      

Sometimes the association method may not be ideal, for many reasons that I will not explain here. It is useful to know this alternative way, which simply uses the ID of the newly created custom instance to create a new address:

User.create(user).then(function(user) {
    var address = {
        street: "somestreet"
        userId: user.userId
    }
    return Address.create(address);
}).then(function(address){
    //do something with address?
}).catch(function(err){
    //do something with your err?
});

      

0


source


You can also use the keyword include

like this:

const user = {
  Username: "John",
  Email: "John@test.com",
  Address: [
    {
      street: "somestreet"
    }
  ]
}

User.create(user, {
    include: [models.address]
})
.then((createdUser) => {
   // ...
})

      

Where models

is an object that contains all of your Sequelize models and their associations.

0


source







All Articles