【问题标题】:Relations in NoSql using mongoDB and MongooseNoSql 中的关系使用 mongoDB 和 Mongoose
【发布时间】:2016-01-21 09:42:10
【问题描述】:

好的,我来自 SQL 背景,我刚刚开始使用 MongoDB 和 Mongoose。

我有两个简单的模型:

汽车:

let mongoose = require('mongoose');
let carsSchema = new mongoose.Schema({
  brand: String,
  specfifications: [String],
  image: String

});
module.exports = mongoose.model('Car', carSchema);

司机

 let mongoose = require('mongoose');
    let Schema    = mongoose.Schema;
    let driverSchema = new mongoose.Schema({

      name: String,
      cars: [{ type: Schema.Types.ObjectId, ref: 'Car' }]

    });
    module.exports = mongoose.model('Driver', driverSchema);

据我所知,这似乎是处理一对多关系的正确方法,在这种关系中,许多司机可以使用一辆车。

现在我需要添加一个名为Races 的类,它将用于保存特定汽车中特定驾驶员的结果。

在 SQL 中思考我会做这样的事情:

let mongoose = require('mongoose');
let raceSchema = new mongoose.Schema({
  totaltime: String,
  laptime: String,
  driver: { type: Schema.Types.ObjectId, ref: 'Driver' },
  car: { type: Schema.Types.ObjectId, ref: 'Car' }

});
module.exports = mongoose.model('Race', raceSchema);

您认为这是在 NoSql 中的正确方法,还是我将我的 SQL 思维方式强加到 NoSQL 中?

【问题讨论】:

    标签: mongodb mongoose nosql


    【解决方案1】:

    答案视情况而定

    MongoDB 或 NoSQL 理论表明,如果所有相关数据都在一个文档中,那么您的查询将运行得更快,因为它们将存储在一起。因此,在大多数情况下,我们希望 Car 和 Driver 使用一个模型

    如果您在大多数查询中没有同时查询汽车和司机(这种情况很少见),那么您所做的也是正确的。

    此外,MongoDB 对文档大小有限制,即 16 MB,如果您认为将它们存储在一起的成本可能超过 16MB,那么您所做的就是正确的。但是,还有另一种解决方案,即 GridFS,它将文档存储成块并克服了这个限制

    【讨论】:

    • 好的,谢谢!因此,您所说的汽车和驾驶员的组合模型。您是否也会在该模型中包含“种族”?
    • 如果可以,那么模型应该按照您的查询方式设计,即,如果您经常一起查询事物并且它们适合 16MB(这对于大多数情况来说已经足够了)
    猜你喜欢
    • 2014-09-25
    • 2015-10-25
    • 1970-01-01
    • 2013-04-02
    • 2017-10-27
    • 2017-10-23
    • 2016-02-17
    • 2013-08-27
    • 1970-01-01
    相关资源
    最近更新 更多