[英]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.