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 };
- 无限的Webpack手表循环 – 如何忽略.js文件的变化等
- 为什么在Node.js中使用util.inherits和.call来inheritance
- 如何将一个CSSselect器转换为JavaScript中的XPath?
- grunt-contrib-watch livereload 35729 livereload.js无法加载
- 在Meteor的客户端和服务器上生成相同的随机数
- 当我们应该使用file.write(…)而不是file.createWriteStream(…)?
- 如何使用id-aes256-GCM与Node.JSencryption? “TypeError:DecipherFinal失败”
- websockets,从服务器的消息更新div
- 需要说明:在JavaScript中用于…和for(;;)时会有不同的输出