MongoDB中的嵌套模式

我刚开始在MongoDB中使用子文档。

我有两个模式

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

我应该为每个模式创build一个模型,还是最好只有一个parentSchema模型?

由于我不想使用关系查询,所以我没有看到为每个模型创build模型的好处。

我会build议你只为Parent创build一个model ,并且可以push Child push入该模型。

在这种情况下, deleting父母也会自动delete孩子。 但是,如果您还为Child创build了另一个模型,则在deleteparent之前,必须delete parent

备用

如果您不想在deletion 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)db / 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)db / 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)db / 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 };