Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a Sequelize model instance, without saving it in the database?

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.

like image 829
Ionică Bizău Avatar asked Mar 27 '17 13:03

Ionică Bizău


People also ask

How do I create an instance in Sequelize?

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.

How do I make a model Sequelize?

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.

Can Sequelize create database if not exists?

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.


1 Answers

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" })
like image 151
Adam Avatar answered Oct 18 '22 22:10

Adam