0
我想嵌入一個文檔,所以我猜一個子文檔,到Mongoose架構。我一直遵循Mongoose documentation提出的這種模式。我的模式看起來像這樣。Mongoose Schema嵌入文檔默認
var CategoriesSchema = new Schema({
name: { type: String, required: true, default: 'default' }
});
var PostSchmea = new Schema({
title: { type: String, required: true, default: 'default title' },
writtenBy: { type: ObjectId, required: true, default: '55878003ebf4b06110ef2ff8' },
publishedOn: { type: Date, default: Date.now },
updatedOn: Date,
published: { type: Boolean, required: true, default: false },
content: { type: String, required: true, default: 'empty' },
category: { type: [CategoriesSchema] },
tags: [String],
images: [String]
});
正如您所看到的,我已將CategoriesSchema嵌入到PostSchema中。我的問題是如何爲PostSchema中的類別鍵設置默認值。我嘗試以下,並得到了錯誤「類型錯誤:無法讀取屬性未定義‘$ __’」:
var PostSchmea = new Schema({
title: { type: String, required: true, default: 'default title' },
writtenBy: { type: ObjectId, required: true, default: '55878003ebf4b06110ef2ff8' },
publishedOn: { type: Date, default: Date.now },
updatedOn: Date,
published: { type: Boolean, required: true, default: false },
content: { type: String, required: true, default: 'empty' },
category: { type: [CategoriesSchema], default: [CategoriesSchema] },
tags: [String],
images: [String]
});
而且我也試過以下,並得到了錯誤「語法錯誤:意外令牌」:
var PostSchmea = new Schema({
title: { type: String, required: true, default: 'default title' },
writtenBy: { type: ObjectId, required: true, default: '55878003ebf4b06110ef2ff8' },
publishedOn: { type: Date, default: Date.now },
updatedOn: Date,
published: { type: Boolean, required: true, default: false },
content: { type: String, required: true, default: 'empty' },
category: { type: [CategoriesSchema], default: new CategoriesSchema(name: "default") },
tags: [String],
images: [String]
});
任何建議或文件將不勝感激。
謝謝,
感謝您的回答!我要測試一下,如果有效,我會告訴你。再次感謝! –
這不適用於貓鼬4+。 存在嵌入文檔無法識別父文件的問題 – lobengula3rd