Let's assume we have an Sequelize model called Person
—how can we create an instance of Person
, without saving it into the database?
This will create the record in the database:
Person.create({ name: "Alice" }).then(..., ...);
How to create a model instance without creating a record for it into the database?
The use-case is for creating multiple documents:
myFamily.addPersons([person1, person2, ...]);
When I try to pass raw objects into that array, an error appears: val.replace is not a function
and as suggested here, the reason could be the fact I pass raw objects.
While I'm interested to know how to solve the problem, I'd want to know how to create Sequelize model instances, without saving them in the database.
There are two ways you can define instance methods with Sequelize: Adding the function to the prototype object. Adding the function to the model created using ES6 class.
Sequelize set up Install Sequelize database driver for the database you would like to use by running one of the commands below. Install npm package Sequelize-CLI. Create a project folder. In your project folder path, run the command below to initialize Sequelize in the folder.
Sequelize + MySQL Database Wrapper Connects to MySQL server using the mysql2 db client and executes a query to create the database if it doesn't already exist.
If you build
one, it won't be saved into the db:
var person = Person.build({ name: "Alice" });
Or you can just instantiate the Person
class:
const person = new Person({ name: "Alice" })
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