NoSql 中使用 mongoDB 和 Mongoose 的关系

Relations in NoSql using mongoDB and Mongoose

好的,我来自 SQL 背景,我只是在使用 MongoDB 和猫鼬。

我有两个简单的模型:

汽车:

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

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

Driver

 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);

据我所知,这似乎是处理 one-to-many-relationship 一辆车可供许多 driver 人使用的正确方法。

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

考虑 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-way 思考 NoSQL?

答案取决于

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

的单一模型

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

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