Record some learning and sharing of using Nest. js to build personal blog. Through using and taking notes, I hope I can learn more solid and master knowledge more skillfully. I have connected the database last time, today I will operate the database to complete my DAO layer.
start
As noted earlier, most of the manipulation of a database using TypeORM is done in the form of objects, rather than directly by writing SQL. Of course, this is not always true, and in some complex scenarios, SQL statements may be required to complete database operations.
Here I use the operation of the database is: TypeORM entity class warehouse manager open operation, this way is simple and convenient, other ways can also visit the official website to understand.
Use in Nest
As mentioned earlier, in Nest, we can retrieve the physical warehouse storage directly in the constructor by writing:
constructor(
@InjectRepository(Article)
private readonly articleRepository: Repository<Article>
) {}
Copy the code
Now you can manipulate the database by accessing this.Articlerepository.
Querying the database
Once we have the warehouse storage of the entity class, we can use it to call the corresponding API to manipulate the database. Next, we will record several common operations.
find
Find methods document describes very detailed, you can take a look at the website, and find methods accept a conditionns parameters directly, this parameter contains a number of query conditions, such as common as follows.
where
Indicates the query conditions, for example:
article.find({ where: { title: 'Hello Nest'}})Copy the code
As shown above, we can find data with title Hello Nest, if not return undefined. In addition, WHERE can be used with built-in operators, such as:
article.find({ where: { title: Like('%Hello%')}})Copy the code
All title data containing Hello will be found above.
select
Indicates the fields that need to be queried. Default values are used for fields that do not exist, for example:
article.find({ select: ['title'.'desc']});Copy the code
Only the title and desc attributes have values in the returned entity class.
relations
This is associative query. When our table is associated (one-to-many, many-to-one, many-to-many, many-to-many), we can easily obtain the associated object by using this attribute, for example:
article.find({ relations: ['category']});Copy the code
When the corresponding article is queried, the corresponding classification of the article will be found together with the value assigned to the corresponding attribute of the article entity class (here is category: category).
The skit and take
These two are mainly used for paging. Take means how many pages to fetch, and skip means how many pages to skip. For example, here I want to complete a paging query with 10 pages per page.
articleRepository.find({
skip: (page - 1) * size,
take: size
})
Copy the code
findOne
The findOne documentation is not very well documented. In the findOne declaration file, we can find a method like this:
findOne(id? :string | number | Date| ObjectID, options? : FindOneOptions<Entity>):Promise<Entity | undefined>;
Copy the code
You can see that there are two optional parameters, the first is id, and the second is a generic interface for FindOneOptions, but forget that. From the above definition, we can see that this method should query the corresponding table data by ID, and return a Promise object or undefined.
findAndCount
This method is also commonly used as a pagination. In addition to having the function of find, it can also find the total number of records in the corresponding condition (not affected by take and SKIP pagination) and return an array: the first parameter is the number of records queried by find, and the second parameter is the total number of records, for example:
const [articles, total] = articleRepository.findAndCount();
// articles: Article[]
// total: number
Copy the code
Add/modify a database
To add and modify database records, I recommend an API: Save. This API can be used to add or modify data. The difference is that: when the incoming entity class has the corresponding ID, it saves the data. If there is no ID, add data. For example:
const article = new Article();
article.title = 'New article';
articleRepository.save(article); // Add a piece of data, assuming a record with id=1 is generated
article.id = 1;
article.title = 'Modify title';
articleRepository.save(article); // select * from 'id' where id=1
Copy the code
Also, the save method is powerful enough to add data to the table corresponding to the associated entity object when the corresponding object exists. Such as:
Article and tag are many-to-many, so there is also a tag table and an associated table that records tags and articles
const article = new Article();
article.title = 'New article';
const tag = new Tag();
tag.title = 'tags';
article.tags = [tag];
articleRepository.save(article); // Add data to the tag table and associated table
Copy the code
Delete the data
Deleting data is very simple and can be achieved by using the delete method in the following three ways:
- Pass one in directly
number
: deletes the correspondingid
The data; - Pass in a
number[]
: deletes all items in the corresponding arrayid
The data; - Pass an object: delete it conditionally, for example:
articleRepository.delete({
title: 'title'
});
Copy the code
conclusion
These are just a few simple ways to manipulate a database through the warehouse storage of entity classes. Once you understand these ways, you can easily do some basic CRUD business.
There are other, even more powerful, ways to manipulate databases, such as EntityManager and Query Builder.
To Be Continue…