2016-09-04 74 views
2

我刚开始在MongoDB中使用子文档。MongoDB中的嵌套模式

我有两个模式

childrenSchema = new Schema({ 
    name: String 
}); 

parentSchema = new Schema({ 
    children: [childrenSchema] 
}); 

我应该给每一个模式的模型或者是它最好还是有parentSchema模式?

因为我不想使用关系查询,所以我没有看到为每个模型创建模型的优势。

回答

0

我会建议你只为Parent创建一个model,并且你可以将pushChild纳入。

在这种情况下,deleting父母也会自动delete孩子。但是,如果您为Child制作了另一个模型,则必须在deleteparent之前为的所有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'}] 
}); 
0

我在这种情况下,

单独的定义,模式模型如下:

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 
};