Home > database >  Do not understand the custom function in Sequelize nodejs
Do not understand the custom function in Sequelize nodejs

Time:12-24

const testUser = await User.create({
            name: "Divya Ranat",
            email: "[email protected]"
        });
        const testBoard1 = await Board.create({
            type: "Wood",
            description: "Round",
            rating: 7
        });
        const testBoard2 = await Board.create({
            type: "Metal",
            description: "Square",
            rating: 9
        });

        await testUser.addBoards([testBoard1, testBoard2]);
        const foundBoards = await testUser.getBoards();


        const foundUser = await testBoard1.getUser();
        console.log(foundUser)

I was expecting the addBoards(), getBoards() and getUser() function to throw an error. I don't understand what the addBoards(), getBoards() and getUser() does too

CodePudding user response:

Your code:

const testUser = await User.create({
            name: "Divya Ranat",
            email: "[email protected]"
        });

returns an sequelize instance to testUser. The instance has the data and several methods/functions.

Example: with

await testUser.update({property: value})

you can update exactly that record in the db, instaead of:

await User.update({property: value},{where: { id })

Now if you use associations between models, sequelize adds functions to the instance like addBoards.

It will throw an error if you pass wrong data.

  • Related