首页 > 解决方案 > Mongoose:在属性中引用模式或添加为数组?哪个更好

问题描述

例如,如果我有两个模式UserPost,我应该在 Post 的属性中添加 User 引用,还是在 User Schema 中添加 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]
});

标签: javascriptnode.jsmongoose

解决方案


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

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


推荐阅读