# VirtualRef Decorator mongoose property

Module
import { VirtualRef } from "@tsed/mongoose"
Source/packages/mongoose/src/decorators/virtualRef.ts

# Overview

function VirtualRef(type: string, foreignField: string): Function;
export function VirtualRef(options: MongooseVirtualRefOptions): Function;
export function VirtualRef(options: string | MongooseVirtualRefOptions, foreignField?: string): Function;
export type VirtualRef<T> = T | null;

# Description

Define a property as mongoose virtual reference to other Model (decorated with @Model).

WARNING

To avoid circular dependencies, do not use the virtual reference model in anything except a type declaration. Using the virtual reference model will prevent typescript transpiler from stripping away the import statement and cause a circular import in node.

# Example

import {Property} from "@tsed/common";
import {Model, Ref, VirtualRef, VirtualRefs} from "@tsed/mongoose";

@Model()
class Person {
  @Property()
  name: string;

  @Property()
  band: string;
}

@Model()
class Band {
  @VirtualRef({
    ref: Person, // The model to use
    localField: "name",  // Find people where `localField`
    foreignField: "band", // is equal to `foreignField`
    // If `justOne` is true, 'members' will be a single doc as opposed to
    // an array. `justOne` is false by default.
    justOne: false,
    options: {} // Query options, see http://bit.ly/mongoose-query-options
  })
  members: VirtualRefs<Person>;
}

@Model()
export class MyRef {
  @VirtualRef("MyModel")
  virtual: VirtualRef<MyModel>;

  @VirtualRef("MyModel")
  virtuals: VirtualRefs<MyModel>;
}

@Model()
export class MyModel {
  @Ref(MyRef)
  ref: Ref<MyRef>;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40