[英]mongoose - how to get subdocument to comply with a schema
所以我有以下模式:
var Item_Detail = new Schema(
{
content: {
index: true,
type: Array
},
is_private: {
default: false,
index: true,
type: Boolean
},
order: {
index: true,
required: true,
type: Number
},
table: {
default: {},
type: Object
},
title: {
required: true,
index: true,
type: String,
},
type: {
default: "text",
enum: ["text", "table"],
index: true,
type: String
},
},
{
strict: false
}
)
const Item = new Schema(
{
details: {
default: [],
index: true,
type: [Item_Detail],
},
display_name: {
default: "",
index: true,
type: String,
},
image: {
default: "http://via.placeholder.com/700x500/ffffff/000000/?text=No%20Image&",
type: String
},
is_private: {
default: false,
index: true,
type: Boolean
},
tags: {
index: true,
type: [Tag]
}
},
{
strict: false
}
)
現在, Item_Detail
將成為Item
的子文檔,但是我不確定如何強制執行default
s和type
限制。 我也不希望Item_Detail
就是一個集合,因此使用create
或save
可能不合適。
我認為您可以為此使用嵌入式文檔 ,因此可以在項目架構中嵌入 item_detail:
const Item = new Schema({
...
item_detail: item_detail
})
然后,在服務器上,當您要添加item_detail時,可以執行以下操作
myItem = new Item({//enter item data here})
//assign item detail here
myItem.item_detail = item_detail ;
然后繼續保存
myItem.save()
強制類型很容易,默認值是一個棘手的值,但是mongoose
允許您指定一個函數而不是boolean作為default
(就像它允許您為required一樣 )。
因此,您可以執行以下操作(為求勇敢,我簡化了架構):
const itemDetails = new Schema({
info: {
type: String,
required: true
}
})
const item = new Schema({
details: {
default: function() {
return [new ItemDetails({ info: 'N/A' })]
},
type: [itemDetails],
}
})
這將允許您執行以下操作:
var itm = new Item();
保存的結果將是:
{
"_id": ObjectId("5b72795d4aa17339b0815b8b"),
"details": [{
"_id": ObjectId("5b72795d4aa17339b0815b8c"),
"info": "N/A"
}]
}
所以這給你兩件事:
itemDetails
之外的details
放置任何類型,因為您已使用itemDetails
強制了該類型。 default
自定義函數中所需的default
值來初始化ItemDetails
對象。 希望這可以幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.