Nodejs sequelize hasOne not working

Issue:
The createCart() function in app.js is allowing multiple carts to be created for a single user when the server is reloaded.

Expected Behavior:
createCart() should only create a single cart per user, regardless of how many times the server is reloaded.

Fenced Code Blocks:

Product.belongsTo(User, { constraints: true, onDelete: 'CASCADE' });
User.hasMany(Product);
User.hasOne(Cart);
Cart.belongsTo(User);
Cart.belongsToMany(Product, { through: CartItem });
Product.belongsToMany(Cart, { through: CartItem });
sequelize
// .sync({ force: true })
    .sync()
    .then(result => {
        return User.findByPk(1);
        // console.log(result);
    })
    .then(user => {
        if (!user) {
            return User.create({ name: 'Max', email: 'test@test.com' });
        }
        return user;
    })
    .then(user => {
        // console.log(user);
        return user.createCart();
    })
    .then(cart => {
        app.listen(4000);
    })
    .catch(err => {
        console.log(err);
    });

The issue is that the createCart() function in app.js is allowing multiple carts to be created for a single user when the server is reloaded. The expected behavior is that createCart() should only create a single cart per user, regardless of how many times the server is reloaded.

To fix the issue, you can modify the createCart() function to check if the user already has a cart before creating a new one. Here is an example of how to do this:

.then(user => {
    return user.getCart();
})
.then(cart => {
    if (cart) {
        return cart;
    }
    return user.createCart();
})
.then(cart => {
    app.listen(4000);
})

This code first calls user.getCart() to check if the user already has a cart. If a cart exists, it returns that cart. If not, it creates a new cart using user.createCart(). This ensures that each user only has one cart, regardless of how many times the server is reloaded.