簡體   English   中英

使用mongoDB和Mongoose的NoSql中的關系

[英]Relations in NoSql using mongoDB and Mongoose

好的,我來自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或NoSQL理論認為,如果所有相關數據都在一個文檔中,那么您的查詢將更快地運行,因為它們將存儲在一起。 因此,在大多數情況下,對於汽車和駕駛員,我們都希望使用一個模型

如果您在大多數查詢中都不同時查詢汽車和駕駛員(這種情況很少見),那么您所做的也是正確的。

另外,MongoDB在文檔大小上有一個限制,即16 MB,如果您認為將它們存儲在一起的成本可能超過16 MB,那么您所做的就是正確的。 但是,還有另一種解決方案,即GridFS,可以將文檔存儲為大塊並克服了此限制

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM