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了另一个模型,则在delete
该parent
之前,必须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 };
- 有一个node.js模块可以确定一个IP的地理位置吗?
- Mongk:带有Monk的Mongo数据库:错误捕获和处理,如果数据库closures
- node.js:程序意外退出或挂起
- 套接字IO | 如何获得服务器端的客户端传输types?
- Sails.js 0.11和护照:“Missing Credentials”错误
- 是否有可能在meteor应用程序中使用本地(未发布)节点模块?
- 将模型导入为对象,而不是在使用Express的Node.js项目中运行
- 将AES Java解密代码移植到Node.js
- 错误:加载firebase.json时出现错误:未安装Bolt,运行npm install -g firebase-bolt