我剛開始在MongoDB中使用子文檔。MongoDB中的嵌套模式
我有兩個模式
childrenSchema = new Schema({
name: String
});
parentSchema = new Schema({
children: [childrenSchema]
});
我應該給每一個模式的模型或者是它最好還是有parentSchema
模式?
因爲我不想使用關係查詢,所以我沒有看到爲每個模型創建模型的優勢。
我剛開始在MongoDB中使用子文檔。MongoDB中的嵌套模式
我有兩個模式
childrenSchema = new Schema({
name: String
});
parentSchema = new Schema({
children: [childrenSchema]
});
我應該給每一個模式的模型或者是它最好還是有parentSchema
模式?
因爲我不想使用關係查詢,所以我沒有看到爲每個模型創建模型的優勢。
我會建議你只爲Parent
創建一個model
,並且你可以將push
Child
納入。
在這種情況下,deleting
父母也會自動delete
孩子。但是,如果您爲Child製作了另一個模型,則必須在delete
即parent
之前爲的所有children
,parent
。
備用
如果你不想上Parent
刪除child
,你應該create
兩型,一爲Parent
,另一個用於Child
,並使用reference
代替sub-document
存儲的孩子。這樣你不必將整個子文檔存儲在父文檔中,只需要_id
就可以了。稍後,您可以使用mongoose populate
來檢索有關小孩的信息。
childrenSchema = new Schema({
name: String
});
var child = mongoose.model('child',childrenSchema);
parentSchema = new Schema({
children: [{type : Schema.Types.ObjectId , ref : 'child'}]
});
我在這種情況下,
單獨的定義,模式模型如下:
1)分貝/ definitions.js:
const
mongoose = require('mongoose'),
Schema = mongoose.Schema,
Child = {
name: {
type: Schema.Types.String,
required: true,
index: true
}
},
Parent = {
name: {
type: Schema.Types.String,
required: true,
index: true
},
children: {
type: [ChildSchemaDefinition],
index: true,
ref: 'Child';
}
};
module.exports = {
Child,
Parent
};
2)分貝/ schemas.js:
const
mongoose = require('mongoose'),
Schema = mongoose.Schema,
definitions = require('./definitions');
Child = new Schema(definitions.Child),
Parent = new Schema(definitions.Parent);
module.exports = {
Child,
Parent
};
3)分貝/models.js:
const
mongoose = require('mongoose'),
Model = mongoose.model,
schemas = require('./schemas');
const
Child = Model('Child', schemas.Child),
Parent = Model('Parent', schemas.Parent);
module.exports = {
Child,
Parent
};