簡體   English   中英

Mongodb Populate 未在 Node.js 中填充文檔

[英]Mongodb Populate is not populating document in Node.js

我正在使用 typegoose,我的QueryQueryRule模型如下。

export class Query {
  @prop()
  queryRule: Ref<QueryRule>;
}
export class QueryRule {
  @prop()
  condition: Condition;

  @prop()
  rules: Ref<QueryRule | ChildRule>[];
}

我正在使用以下查詢進行填充。

await QueryModel.findById(queryId).populate('queryRule');

我的查詢文件如下。

{"_id":{"$oid":"6283d73baffa60c38af8c2f0"},"name":"test","queryRule":{"$oid":"6287c8f0e3ab4b5dd7238ef3"}}

我的 QueryRule 文檔如下。

{"_id":{"$oid":"6287c8f0e3ab4b5dd7238ef3"},"condition":1,"rules":[],"__v":0}

但是當我使用填充查詢訪問 QueryRule 的conditionrules時。 即使該文檔中存在值,我也未定義。

我在這里做錯了什么?

您的問題似乎是您缺少必需的選項ref ,請參閱 Typegoose 文檔中的引用其他類

在您的情況下,您的代碼應該看起來更像:

export class Query {
  @prop({ ref: () => QueryRule })
  queryRule: Ref<QueryRule>;
}

export class QueryRule {
  @prop()
  condition: Condition;

  //@prop({ ref: () => QueryRule })
  //rules: Ref<QueryRule | ChildRule>[];
}

至於Ref<QueryRule | ChildRule>[] Ref<QueryRule | ChildRule>[] ,您要么必須將其限制為 2 種可能性中的一種,要么使用鑒別器,請參閱 Typegoose 文檔中的非嵌套鑒別器。

另外作為一個小旁注,如果您的condition: Condition也不是 typegoose 類,它將變為Mixed ,這在運行時基本上是any類型的貓鼬。

為此,我需要兩件事。

  1. 首先是我錯過了{ ref: () => QueryRule }
  2. 然后在填充中我必須像這樣傳遞模型{ path : 'queryRule', model: QueryRuleModel }
export class Query {
  @prop({ ref: () => QueryRule })
  queryRule: Ref<QueryRule>;
}
let query: Query = await QueryModel
      .findById(queryId)
      .populate({ path : 'queryRule', model: QueryRuleModel });
@prop({
  ref: () => QueryRule | ChildRule,
  required: true
})
rules: Ref<QueryRule | ChildRule>[];

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM