TypeORM Find By Id with MongoDB


Example collection video

[_id] => MongoId Object (
    [$id] => 5f7595f58ef2bc0779051346
)
[ID] => 16275152
[thumb] => https://thumb.tutorialspots.com/a/Hebe-vBz-7GPC5NyA23Sng/016/275/152/240x135.s.jpg
[duration] => 737
[link] => /videos/my-video-1
[title] => My Video 1
[views] => 17306
[like] => 16960
[hd] => 1
[tags] => Array (    
)
[categories] => Array (
)
[type] => 1
[_id] => MongoId Object (
    [$id] => 5f7595f58ef2bc0779051347
)
[ID] => 16276663
[thumb] => https://thumb.tutorialspots.com/a/sDzRZN15I6dYJvfaHzGD8w/016/276/663/240x135.s.jpg
[duration] => 809
[link] => /videos/my-video-2
[title] => My Video 2
[views] => 102839
[like] => 100782
[hd] => 1
[tags] => Array (
)
[categories] => Array (
)
[type] => 2

Example TypeScript works with NestJS

import { ObjectID } from "mongodb";
...
  @Post("history/:page")
  @Render("postHistory")
  async postHistory(@Body('ids') ids,@Param('page') page){
    let take = 10, skip = (page-0)*take 
    let videos = await this.videoService.findAll({
      take, skip, where: {
        _id: {$in: Object.keys(ids).map(a=>new ObjectID(a))}
      }
    }); 
    return {      
      videos
    }
  }

Example CommonJS with method find

	const mongodb = require("mongodb");
    ...
    const videoRepository = getMongoRepository(video);
    let videos = await videoRepository.find({      
        _id: {$in: [
			new mongodb.ObjectID("5f7595f58ef2bc0779051346"),
			new mongodb.ObjectID("5f7595f58ef2bc0779051347")
		]}      
    })

Example CommonJS with method findOneById

	const mongodb = require("mongodb");
	...
    const videoRepository = getMongoRepository(video);
    let video = await videoRepository.findOneById(new mongodb.ObjectID("5f7595f58ef2bc0779051346"))

Leave a Reply