I have created my models fro sequelize. I've got a User model which attached as an Address object. The links are defined as such:
User.hasMany(Address);
Address.belongsTo(User);
The object I am trying to store has the right structure with the child attached:
{
Username: "John",
Email: "[email protected]",
Address: [{
street: "somestreet"
}]
};
When I try to create the object, the parent is inserted in my database, but the app exits with a [sequelize object] does not contain method .save()
I am creating as follows:
User.create(user).success(function(user){
});
I have got logging enabled on my sequelize instance and I can see the correct sql being generated for the parent object, but I am stuck on how to properly store the child (associated) object.
You can also use the include
keyword like so:
const user = {
Username: "John",
Email: "[email protected]",
Address: [
{
street: "somestreet"
}
]
}
User.create(user, {
include: [models.address]
})
.then((createdUser) => {
// ...
})
Where models
is an object that holds all your Sequelize models and their associations.
I don't think you can create an associated object like this.
Other things: You shouldn't use the success handler anymore. User .then
, .catch
and .finally
instead.
I am assuming that you have a primary key userId
for your User
model. Else replace userId
in the below example with your primary key, which might be Username
.
You should do:
var user = {
Username: "John",
Email: "[email protected]"
};
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 which I shan't explain here. Its good to know this alternate way, which is simply to use the id of the newly created user instance to make the 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?
});
Turns out the original comment by Wrikken was correct, I was passing in a sole object rather then an array.
This fixed it:
{
Username: "John",
Email: "[email protected]",
Address: [{
street: "somestreet"
}]
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With