typeorm/docs/mongodb.md
Umed Khudoiberdiev 3b8a031ece
0.3.0 (#8616)
* added find options and new option relationLoadStrategy

* find now returns null instead of undefined; removed primary relations support; bugfixing; added some changes and tests from next branch;

* added typename to connection options; added data loader types, lot of deprecations; new es2020 emit by tsc; new custom repositories syntax

* applied lint fixing

* replaced some instanceof checks

* reverting docker compose image versions

* optimizing imports

* reverting back some instanceof checks to prevent compiler errors

* downgrading es compilation version

* docs: remove "primary" from relation options (#8619)

remove ex-line 26 for being deprecated in 0.3.0:
"* `primary: boolean` - Indicates whether this relation's column will be a primary column or not."

* Revert "reverting back some instanceof checks to prevent compiler errors"

This reverts commit 7bf12a39e2297d097aa2a42989afd0e9e4f49bb0.

* Revert "optimizing imports"

This reverts commit 7588ac14e4f1bf1a82e3b7883134b9c2c8ae5f3f.

* Revert "replaced some instanceof checks"

This reverts commit bfa5a2d706f697ed1c1beb38b4455c0d33121e5a.

* fixing few comments

* removing transaction decorators

* this test is invalid - it's not clear why the hell getTreeRepository will throw an error and it's not clear what kind of error its going to throw

* addded mixed list support in connection options

* trying to fix oracle length issue

* lintfix

* removed shorten usages

* added named entity target support to the connection

* fixing entity target support in relation options via entity schema

* debugging oracle issue

* fixed issue with alias not being shortened in many to many alias cases

* some day we'll have a prettier.

* fixing oracle tests

* fixing oracle failing test

* removed "null" support in where expressions; fixed softDelete and restore incorrect usages

* renamed FindConditions to FindOptionsWhere

* version bump

* docs: update loading relation in find method (v 0.3.0) (#8621)

* docs: update relation definition method

Update the method that allows loading a specific relation inside the find method.
This method is found on the one-to-one-relations page.
Change `const users = await userRepository.find({ relations: ["profile"] });` to `const users = await userRepository.find({ relations: {profile: true});`.

* fix formatting

Co-authored-by: Umed Khudoiberdiev <pleerock.me@gmail.com>

* docs: change relations option definition (#8620)

* docs: change relations option definition

change line 139 from 
`const users = await connection.getRepository(User).find({ relations: ["profile", "photos", "videos"] });`
to
`const users = await connection.getRepository(User).find({ relations: { profile: true, photos: true, videos: true] });`
to reflect version 0.3.0 changes

* docs: change relations option definition

Rectified a type on line 139
from:
`const users = await connection.getRepository(User).find({ relations: { profile: true, photos: true, videos: true] });`
to
`const users = await connection.getRepository(User).find({ relations: { profile: true, photos: true, videos: true} });`

* formatting

Co-authored-by: Umed Khudoiberdiev <pleerock.me@gmail.com>

* lint

* improved find options types

* fixed types and removed nonnever because it causes circual issue for some reason

* docs: update entitymanager definition (#8623)

* docs: update entitymanager definition

change the "What is EntityManager?" page to be up-to-date with v 0.3.0

1. line 6 changes from
`You can access the entity manager via 'getManager()' or from 'Connection'.`
to 
`You can access the entity manager via DataSource's manager.`

2. the import on `getManager` in line 10 becomes `Manager` that the user have configured beforehand:
`import {getManager} from "typeorm";`
becomes 
`import {Manager} from "./config/DataSource";`

3.change entityManager definition in line 13:
from
`const entityManager = getManager(); // you can also get it via getConnection().manager`
to
`const entityManager = Manager;`

* docs: update entitymanager definition

changed line 10 from: 
`import {Manager} from "./config/DataSource";`
to
`import {DataSource} from "typeorm";`

and changed line 13 and 14 from: 
`const entityManager = Manager;`
`const user = await entityManager.findOne(User, 1);`
to 
`const myDataSource = new DataSource({ /*...*/ });`
`const user = await myDataSource.manager.findOne(User, 1);`

for a simpler way of describing the origin of DataSource and how it works.

* In return type doesn't seem to work in all cases

* feat: mssql v7 support (#8592)

Adds support for v7 of the mssql library as v6 is EOL. This also makes use of the new toReadableStream method on requests to return a native stream where required.

* fix: prefix relation id columns contained in embedded entities (#6977) (#7432)

* fix: prefix relation id columns contained in embedded entities (#6977)

Searches embedded entity columns for relation ID column if relation column
is in embedded entity. If not found, creates new relation ID with embedded
metadata set to match the relation column.

fixes: #2254
fixes: #3132
fixes: #3226
fixes: #6977

* test: prefix subcounters sub-entity with "sub" to fit in 30 character identifier for oracle

Problem introduced with #6981

* fix: find by Date object in sqlite driver (#7538)

* fix: find by Date object in sqlite driver

In sqlite, Date objects are persisted as UtcDatetimeString.
But a Date object parameter was escaped with .toISOString(), making such queries impossible.
This commit aligns both transforms.
This bug does *not* apply to better-sql where you can only bind numbers, strings, bigints, buffers,
and null.
This is breaking for when the user inserted their dates manually as ISO and relied on this old
maltransformation, after this their find()s by Date won't work anymore.

BREAKING CHANGE: Change Date serialization in selects
Closes: #2286

* add failing test

* fix: find by Date object in sqlite driver (with query builder)

Also consider query builder parameter escaping

* test: add test for 3426

Co-authored-by: James Ward <james@notjam.es>

* manually ported changes from #7796

* updated changelog

* fixes after merge

* new findOne syntax

* new find* syntax

* new find* syntax

* lint

* tsc version bump

* tsc version bump and fixed mongodb issues

* moved date fns into non dev deps

* returned oracledb dep into place

* removed lock files

* returned lock files back

* eslint upgrade

* fixing mongodb issue

* fixing mongodb issue

* test: keep junction aliases short (#8637)

Tests a fix for an issue where junction aliases (e.g. in many-to-many relations)
are not unique because they are too long and thus truncated by the driver.

Closes: #8627
Related to: 76cee41dcf1c146d02715c7f48fed33672d28c67

* fixing mongodb issues

* fixing sqlite test

* fixing sqlite test

* fixing sqlite test

* fixing mongodb test

* fixing entity schema tests

* fixing entity schema tests

* merged latest master

* removed driver instanceof checks

* removed function instanceof checks

* removed Object instanceof checks

* removing instanceof checks...

* fixing instanceof checks

* added InstanceChecker to remove remaining instanceof checks

* fixed failing test

* linting

* fixing failing test

* version bump

* compiler fixes

* Connection type usages replace to DataSource

* updated dev deps

* updated deps, add prettier, removed oracledb due to m1 issue

* chalk downgrade

* fixing failing test

* applied prettier formatting

* replaced eslint to prettier

* okay I think we can call it lint

* fixing linting

* fixed prettier introduced compiler bug

* fixed failing test

* prettier;

* fixed failing test

* alias shortening only for junction tables;
fixed failing tests;

* changed aurora db names and reverted change of junction table name shorten algorithm

* format

* removed platform from docker compose

* made numeric parameters to not use parameters to prevent parameters number limit issue. Also enabled shorten only for junction tables

* fixing test

* fixing returning columns bugs

* fixing test

* fixed returning issue

* fixing merge conflicts

* updating documentation

* working on docs / improving api

* working on docs

* fixed isConnected issue

* re-worked commands

* commenting cli command tests for now

* commenting cli command tests for now

* removed platform

* returned Connection back

* refactor: export tree repository helper methods (#8753)

* Migrated protected tree methods to util class

* Added tree repository extend override

* Ran prettier format

* merge master into 0.3.0

Co-authored-by: Bitcollage <serkan.sipahi@yahoo.de>

* working on documentation

Co-authored-by: Bilel Taktak <47742269+Parsath@users.noreply.github.com>
Co-authored-by: Salah Azzouz <52634440+Salah-Azzouz@users.noreply.github.com>
Co-authored-by: Daniel Hensby <dhensby@users.noreply.github.com>
Co-authored-by: Nebojša Cvetković <nebkat@gmail.com>
Co-authored-by: Philip Waritschlager <philip+github@waritschlager.de>
Co-authored-by: James Ward <james@notjam.es>
Co-authored-by: Felix Gohla <37421906+felix-gohla@users.noreply.github.com>
Co-authored-by: Dmitry Zotov <dmzt08@gmail.com>
Co-authored-by: Jimmy Chen <50786287+Q16solver@users.noreply.github.com>
Co-authored-by: Bitcollage <serkan.sipahi@yahoo.de>
2022-03-17 21:01:45 +05:00

8.9 KiB

MongoDB

MongoDB support

TypeORM has basic MongoDB support. Most of TypeORM functionality is RDBMS-specific, this page contains all MongoDB-specific functionality documentation.

Defining entities and columns

Defining entities and columns is almost the same as in relational databases, the main difference is that you must use @ObjectIdColumn instead of @PrimaryColumn or @PrimaryGeneratedColumn.

Simple entity example:

import { Entity, ObjectID, ObjectIdColumn, Column } from "typeorm"

@Entity()
export class User {
    @ObjectIdColumn()
    id: ObjectID

    @Column()
    firstName: string

    @Column()
    lastName: string
}

And this is how you bootstrap the app:

import { DataSource } from "typeorm"

const myDataSource = new DataSource({
    type: "mongodb",
    host: "localhost",
    port: 27017,
    database: "test",
})

Defining subdocuments (embed documents)

Since MongoDB stores objects and objects inside objects (or documents inside documents) you can do the same in TypeORM:

import { Entity, ObjectID, ObjectIdColumn, Column } from "typeorm"

export class Profile {
    @Column()
    about: string

    @Column()
    education: string

    @Column()
    career: string
}
import { Entity, ObjectID, ObjectIdColumn, Column } from "typeorm"

export class Photo {
    @Column()
    url: string

    @Column()
    description: string

    @Column()
    size: number

    constructor(url: string, description: string, size: number) {
        this.url = url
        this.description = description
        this.size = size
    }
}
import { Entity, ObjectID, ObjectIdColumn, Column } from "typeorm"

@Entity()
export class User {
    @ObjectIdColumn()
    id: ObjectID

    @Column()
    firstName: string

    @Column()
    lastName: string

    @Column((type) => Profile)
    profile: Profile

    @Column((type) => Photo)
    photos: Photo[]
}

If you save this entity:

import { getMongoManager } from "typeorm"

const user = new User()
user.firstName = "Timber"
user.lastName = "Saw"
user.profile = new Profile()
user.profile.about = "About Trees and Me"
user.profile.education = "Tree School"
user.profile.career = "Lumberjack"
user.photos = [
    new Photo("me-and-trees.jpg", "Me and Trees", 100),
    new Photo("me-and-chakram.jpg", "Me and Chakram", 200),
]

const manager = getMongoManager()
await manager.save(user)

Following document will be saved in the database:

{
    "firstName": "Timber",
    "lastName": "Saw",
    "profile": {
        "about": "About Trees and Me",
        "education": "Tree School",
        "career": "Lumberjack"
    },
    "photos": [
        {
            "url": "me-and-trees.jpg",
            "description": "Me and Trees",
            "size": 100
        },
        {
            "url": "me-and-chakram.jpg",
            "description": "Me and Chakram",
            "size": 200
        }
    ]
}

Using MongoEntityManager and MongoRepository

You can use the majority of methods inside the EntityManager (except for RDBMS-specific, like query and transaction). For example:

const timber = await myDataSource.manager.findOneBy(User, {
    firstName: "Timber",
    lastName: "Saw",
})

For MongoDB there is also a separate MongoEntityManager which extends EntityManager.

const timber = await myDataSource.manager.findOneBy(User, {
    firstName: "Timber",
    lastName: "Saw",
})

Just like separate like MongoEntityManager there is a MongoRepository with extended Repository:

const timber = await myDataSource.getMongoRepository(User).findOneBy({
    firstName: "Timber",
    lastName: "Saw",
})

Use Advanced options in find():

Equal:

const timber = await myDataSource.getMongoRepository(User).find({
    where: {
        firstName: { $eq: "Timber" },
    },
})

LessThan:

const timber = await myDataSource.getMongoRepository(User).find({
    where: {
        age: { $lt: 60 },
    },
})

In:

const timber = await myDataSource.getMongoRepository(User).find({
    where: {
        firstName: { $in: ["Timber", "Zhang"] },
    },
})

Not in:

const timber = await myDataSource.getMongoRepository(User).find({
    where: {
        firstName: { $not: { $in: ["Timber", "Zhang"] } },
    },
})

Or:

const timber = await myDataSource.getMongoRepository(User).find({
    where: {
        $or: [{ firstName: "Timber" }, { firstName: "Zhang" }],
    },
})

Querying subdocuments

const users = await myDataSource.getMongoRepository(User).find({
    where: {
        "profile.education": { $eq: "Tree School" },
    },
})

Querying Array of subdocuments

// Query users with photos of size less than 500
const users = await myDataSource.getMongoRepository(User).find({
    where: {
        "photos.size": { $lt: 500 },
    },
})

Both MongoEntityManager and MongoRepository contain lot of useful MongoDB-specific methods:

createCursor

Creates a cursor for a query that can be used to iterate over results from MongoDB.

createEntityCursor

Creates a cursor for a query that can be used to iterate over results from MongoDB. This returns a modified version of the cursor that transforms each result into Entity models.

aggregate

Execute an aggregation framework pipeline against the collection.

bulkWrite

Perform a bulkWrite operation without a fluent API.

count

Count number of matching documents in the db to a query.

createCollectionIndex

Creates an index on the db and collection.

createCollectionIndexes

Creates multiple indexes in the collection, this method is only supported in MongoDB 2.6 or higher. Earlier version of MongoDB will throw a command not supported error. Index specifications are defined at http://docs.mongodb.org/manual/reference/command/createIndexes/.

deleteMany

Delete multiple documents on MongoDB.

deleteOne

Delete a document on MongoDB.

distinct

The distinct command returns a list of distinct values for the given key across a collection.

dropCollectionIndex

Drops an index from this collection.

dropCollectionIndexes

Drops all indexes from the collection.

findOneAndDelete

Find a document and delete it in one atomic operation, requires a write lock for the duration of the operation.

findOneAndReplace

Find a document and replace it in one atomic operation, requires a write lock for the duration of the operation.

findOneAndUpdate

Find a document and update it in one atomic operation, requires a write lock for the duration of the operation.

geoHaystackSearch

Execute a geo search using a geo haystack index on a collection.

geoNear

Execute the geoNear command to search for items in the collection.

group

Run a group command across a collection.

collectionIndexes

Retrieve all the indexes on the collection.

collectionIndexExists

Retrieve if an index exists on the collection

collectionIndexInformation

Retrieves this collections index info.

initializeOrderedBulkOp

Initiate an In order bulk write operation, operations will be serially executed in the order they are added, creating a new operation for each switch in types.

initializeUnorderedBulkOp

Initiate a Out of order batch write operation. All operations will be buffered into insert/update/remove commands executed out of order.

insertMany

Inserts an array of documents into MongoDB.

insertOne

Inserts a single document into MongoDB.

isCapped

Returns if the collection is a capped collection.

listCollectionIndexes

Get the list of all indexes information for the collection.

mapReduce

Run Map Reduce across a collection. Be aware that the inline option for out will return an array of results not a collection.

parallelCollectionScan

Return N number of parallel cursors for a collection allowing parallel reading of entire collection. There are no ordering guarantees for returned results

reIndex

Reindex all indexes on the collection Warning: reIndex is a blocking operation (indexes are rebuilt in the foreground) and will be slow for large collections.

rename

Changes the name of an existing collection.

replaceOne

Replace a document on MongoDB.

stats

Get all the collection statistics.

updateMany

Updates multiple documents within the collection based on the filter.

updateOne

Updates a single document within the collection based on the filter.