當我添加虛擬呼叫子域以填充另一個集合中的資料時,我在我的專案中使用 mongoose 和typescript as any).subdomains)但是當列印console.log(r as any)時沒有稱為子域的欄位,請檢查示例 1 和示例 2
export interface IDomain{
domain:string
owner:Schema.Types.ObjectId,
}
const domainSchema = new Schema<IDomain>({
domain:{type:String,required:true},
owner:{type:Schema.Types.ObjectId,required:true},
})
domainSchema.virtual("subdomains",{
ref:"DomainMonitor",
localField: '_id',
foreignField: 'owner'})
查詢資料庫 | 示例 1
Domain.findOne({owner:"633ebe32d0733c0a8eb4f8d6"}).populate("subdomains").then(r=>{
console.log(domains)
})
輸出 | 示例 1
{
_id: new ObjectId("6342fa2d4b730f004704eb45"),
domain: 'dummy.com',
__v: 0,
owner: new ObjectId("633ebe32d0733c0a8eb4f8d6")
}
查詢資料庫 | 示例 2
Domain.findOne({owner:"633ebe32d0733c0a8eb4f8d6"}).populate("subdomains").then(r=>{
const domains= (r as any).subdomains
console.log(domains)
})
輸出 | 示例 2
[{
_id: new ObjectId("6342fa314b730f004704eb47"),
owner: new ObjectId("6342fa2d4b730f004704eb45"),
subdomain: [
'dummy',
],
wildcard: [ '*.dummy.com', '*.dummy.com' ],
__v: 1
}]
uj5u.com熱心網友回復:
將架構表示為物件而不是 JSON(使用 .-operator)的另一種方法如下:
// create a new schema
const MessageSchema = new mongoose.Schema(
{
channel: { type: String },
content: { type: String, required: true },
moderator: { type: Number },
},
// Add this to your Schema
{
toObject: { virtuals: true },
// alternatively: toJSON: { virtuals: true}, if you want your output as json
}
);
// Approach 2:
const mySchema = new mongoose.Schema({
domain: { type:String, required:true },
owner: { type:Schema.Types.ObjectId, required:true }
});
mySchema.set('toObject', { virtuals: true })
貓鼬檔案說:
請記住,默認情況下,虛擬物件不包含在 toJSON() 和 toObject() 輸出中。如果您希望在使用 Express 的 res.json() 函式或 console.log() 等函式時顯示填充虛擬,請在架構的 toJSON 和 toObject() 選項上設定 virtuals: true 選項。
uj5u.com熱心網友回復:
原因在 mongoose 檔案 ( https://mongoosejs.com/docs/guide.html ) 中有說明:
如果你使用 toJSON() 或 toObject() mongoose 默認不會包含虛擬物件。這包括在 Mongoose 檔案上呼叫 JSON.stringify() 的輸出,因為 JSON.stringify() 呼叫 toJSON()。將 { virtuals: true } 傳遞給 toObject() 或 toJSON()。
基本上,您的console.log宣告默認情況下會呼叫toJSON且不包括 virtuals。
您可以在架構定義中包含以下內容,以便在toJSON呼叫中包含虛擬物件:
domainSchema.set('toJSON', { virtuals: true });
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/515583.html
下一篇:使用htaccess縮短url
