【问题标题】:Whats Best way to Model following Mongodb Model遵循 Mongodb 模型的最佳建模方法是什么
【发布时间】:2019-01-12 17:32:56
【问题描述】:

我有两个这样的模型

const testRunSchema = new mongoose.Schema({
    testTimeSlot: {
        type: String,
        required: true
    },
    testDate: {
        type: String,
        required: true
    },
    diagnosticData: [Object],
    notes: String,
    active: {
        type: Boolean,
        default: true
    }
}, {
    timestamps: true,
    strict: false
})

const testingSchema = new mongoose.Schema({
    testId: {
        type: mongoose.Schema.ObjectId,
        required: true
    },

    testDetails: {
        //dummy data
    },
    contactDetails: {
        //dummy data
    },
    testRunDetails: [testRunSchema], //is this a best way?
    runByAssistant: Boolean
}, {
    timestamps: true
});

module.exports = mongoose.model('Testing', testingSchema)

现在我想使用第二个模型的testId 访问testTimeSlot(这是第一个模型)。

我的解决方案:

我可以使用testId访问第一个模型的testimeSlot,因为第一个模型的数据在seconf模型的testRunDetails中可用。

这个解决方案的问题:

由于testRunSchema在第二个模型中被定义为一个数组,因此访问每个数组元素的testTimeSlot并不容易和高效。

解决此问题的最佳方法是什么?

【问题讨论】:

    标签: node.js mongodb mongoose mongoose-schema mongoose-populate


    【解决方案1】:

    您认为正确的是,访问它们并不容易,除了数组填充得越多,查询就越慢。因此,如果您将 testRunSchema 分开并将其数据的引用保存到 testingSchema 中会更好

    const testingSchema = new mongoose.Schema({
        testId: {
            type: mongoose.Schema.ObjectId,
            required: true
        },
    
        testDetails: {
            //dummy data
        },
        contactDetails: {
            //dummy data
        },
        testRunDetails:{
              type:[Schema.Types.ObjectId], ref:'testRunSchema'
        },//like this in here the object id of testRunSchema 
    
        runByAssistant: Boolean
    }, {
        timestamps: true
    });
    

    当你想查询时,你只需要在mongoose中使用polulate() 你可以在here阅读它

    【讨论】:

    • testRunDetails: [Schema.Types.ObjectId]testRunDetails: [{type:Schema.Types.ObjectId, ref:'testRunSchema'}] 有什么区别
    • ref 告诉我们在填充时使用什么模型
    • 对不起,我忘了把它放在答案中。现在检查一下,我已经编辑了它。希望这有帮助
    • ref 关键字应该在里面吧? testRunDetails: [{type:Schema.Types.ObjectId, ref:'testRunSchema'}]
    • 是的,应该是
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-06-07
    • 1970-01-01
    • 2018-03-17
    • 2021-10-01
    • 2015-10-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多