Mongoose:在属性中引用模式还是作为数组添加?哪个更好



例如,如果我有两个架构UserPost,我应该在Post的属性中添加User引用,还是在UserSchema中添加Post架构作为数组?这在性能方面(以及其他方面(更好。

var PostSchema = new mongoose.Schema({
title: String,
postedBy: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
},
});

var UserSchema = new mongoose.Schema({
name: String,
posts: [PostSchema]
});
var PostSchema = new mongoose.Schema({
title: String,
postedBy: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
},
});

我认为这种方式比其他方式更好。

您应该在PostSchema中有一个对用户的引用。

这是更好的方法,因为用户可以有多个帖子,如果将UserSchema中的帖子保存为一个数组,则该数组可以无限增长。这可能会导致问题,因为mongodb文档的最大大小有限制。单个mongodb文档不能大于16Mb。

从性能的角度来看,将Posts保存在User模式中更好,但考虑到mongodb文档的大小限制以及用户可以有多个Posts的事实,引用其父文档(User(的子文档(Post(是更好的方法。

最新更新