簡體   English   中英

Mongoose:設置默認填充選項

[英]Mongoose: setting default populate options

我在 mongoose 中有一個架構,它引用了另一個架構,例如:

OrderSchema = new Schema({
  createdBy: {
     ref: 'User',
     type: ObjectId
  }
})

在我的用戶模式中,我使用軟刪除插件來保留引用。 對於普通用戶查找查詢,插件使用預查找掛鈎將 where {deleted: {$ne: true}} 添加到查詢中。

當我嘗試查找填充了 createdBy 的所有訂單時,也會應用已刪除的查詢,以便不會填充任何(軟)刪除的用戶。 我可以通過在填充選項中提供“includeDeleted”參數來繞過軟刪除查詢,這對於特定查詢很有效。

我希望能夠在架構定義中指定此選項,以便我不依賴每個查詢來包含選項,例如:

// doesnt work, options are not supplied to populate query
OrderSchema = new Schema({
  createdBy: {
     ref: 'User',
     type: ObjectId,
     options: {
       includeDeleted: true
     }
  }
})

虛擬填充確實以這種方式工作:

// WORKS
OrderSchema.virtual('_createdBy', {
   ref: 'User',
   ...,
   options: {
      includeDeleted: true
   }
})

也許還有其他選項可以在架構定義中提供默認填充選項? 我無法在文檔中找到任何內容。

另一種解決方案是在軟刪除插件中手動查找人口選項,但這需要我知道查詢是否是預查找掛鈎中的“人口查詢”。

https://mongoosejs.com/docs/schematypes.html

填充:Object,設置默認填充選項

這可能會有所幫助。 我認為你應該這樣使用它

OrderSchema = new Schema({
createdBy: {
 ref: 'User',
 type: ObjectId,
 populate: {
   includeDeleted: true
 }
 }
})

暫無
暫無

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

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