【发布时间】:2019-08-01 10:11:28
【问题描述】:
此语法直接来自关于子类型的 mongoose 文档。但是,我也看到了这个对子文档的替代参考。有什么区别?
https://mongoosejs.com/docs/subdocs.html
var childSchema = new Schema({ name: 'string' });
var parentSchema = new Schema({
// Array of subdocuments
children: [childSchema],
// Single nested subdocuments. Caveat: single nested subdocs only work
// in mongoose >= 4.2.0
child: childSchema
});
对子文档的另一种引用方式
var childSchema = new Schema({ name: 'string' });
mongoose.model('children', childSchema);
var parentSchema = new Schema({
children: {
type: Schema.Types.ObjectId,
ref: 'children'
},
});
【问题讨论】:
-
是的,所以在第二种情况下,您只是获取文档的 _id 而不是整个文档本身。所以它在文档存储方面要便宜得多,另外,您还可以使用
.populate方法执行类似联接的操作,这比 mongodb 聚合$lookup更快。
标签: mongodb mongoose mongoose-schema