MongoDB中的嵌套模式

Nested schemas in MongoDB

本文关键字:模式 嵌套 MongoDB      更新时间:2023-09-26

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

我有两个模式

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

我应该为每个模式创建一个模型吗?还是最好只为parentSchema创建一个模型?

我不认为为每个查询创建模型有什么好处,因为我不想使用关系查询。

我建议您只为Parent创建一个model,并且您可以将push Child放入其中。

在这种情况下,deleting父将自动delete子。但是,如果您也为Child制作另一个模型,则必须在delete parent之前delete parent的所有children

如果你不想在Parentdeletion上删除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
};