2015-07-28 72 views
0

我正在試驗我與Mongoose的第一次關係測試,我想知道在繼續之前我是否正在做事情。我的ManyToOne關係是否正確?

我有兩個模型:一個Galaxy和一個StarSystem。 Galaxy有許多StarSystems,StarSystem有一個Galaxy。

這裏是我的模型:

銀河:

var mongoose = require('mongoose'); 
var Schema = mongoose.Schema; 

var galaxySchema = new Schema({ 
    name: { 
     type: String, 
     required: true 
    }, 
    planets: [{ 
     type: Schema.Types.ObjectId, 
     refs: 'StarSystem' 
    }] 
}); 

var Galaxy = mongoose.model('Galaxy', galaxySchema); 

module.exports = Galaxy; 

StarSystem:

var mongoose = require('mongoose'); 
var Schema = mongoose.Schema; 

var starSystemSchema = new Schema({ 
    name: { 
     type: String, 
     required: true 
    }, 
    xPosition: { 
     type: Number, 
     required: true 
    }, 
    yPosition: { 
     type: Number, 
     required: true 
    }, 
    starType: { 
     type: Number, 
     required: true, 
     min: 0, 
     max: 7 
    }, 
    galaxy: { 
     type: Schema.Types.ObjectId, 
     ref: 'Galaxy', 
     required: true 
    } 
}); 

var StarSystem = mongoose.model('StarSystem', starSystemSchema); 

module.exports = StarSystem; 

StarSystem路線:

var router = require('express').Router(); 
var config = require('../config'); 
var StarSystem = require('../models/star_system'); 
var Galaxy = require('../models/galaxy'); 

router.get('/', function(req, res) { 
    StarSystem.find().exec(function(err, starSystems) { 
     res.json(starSystems); 
    }); 
}); 

router.get('/:id', function(req, res) { 
    StarSystem.findById(req.params.id, function(err, starSystem) { 
     if (undefined === starSystem) { 
      res.status(404).json({ 
       message: 'Star System not found.' 
      }); 
     } 
     else { 
      res.json(starSystem); 
     } 
    }); 
}); 

router.post('/', function(req, res) { 
    var starSystem = new StarSystem(req.rawBody); 

    starSystem.save(function(err, starSystem) { 
     if (null != err) { 
      res.status(500).json(err); 
     } 
     else { 
      res.status(201).json({ 
       location: config.app.domain + '/star-systems/' + starSystem._id 
      }); 
     } 
    }); 

    Galaxy.findById(req.rawBody.galaxy, function(err, galaxy) { 
     galaxy.planets.push(starSystem); 
     galaxy.save(); 
    }); 
}); 

module.exports = router; 

我的問題是專門關於我處理的方式廣告在「POST」方法中將星系轉換爲Galaxy。我目前將它添加到數組中,但我不知道是否有更快/更容易的東西。我將不勝感激任何有關我的代碼的建議。

+0

我注意到你沒有接受或評論我的答案呢。當我能夠幫助你時,請接受我的答案。當我無法幫助你時,請評論告訴我你需要的其他信息。 – Philipp

回答

0

你應該問自己,爲什麼你首先從星系到星系有一個參考。

當您檢索到一個Galaxy對象時,所有關於它的明星系統的信息都是_id列表。 _id單獨提供您的應用程序,除了可能知道有多少。要獲取有關星形系統的任何有用數據,您需要對StarSystem集合執行後續查詢以解析引用。

因此,無論如何,當您需要查詢StarSystem集合時,您可以並行執行此操作,同時您仍在等待Galaxy的結果,方法是找到StarSystemgalaxy:galaxyId

這不僅僅是更快,它還提高了一致性(不可能出現矛盾的StarSystem-> Galaxy和Galaxy-> StarSystem參考),最重要的是它阻止了Galaxy對象的增長。 MongoDB不喜歡增長的對象,因爲無論何時對象增長到其大小的兩倍時,數據庫都需要從硬盤驅動器中刪除它並將其附加到文件末尾,這會降低寫入性能。

引用數組可能有用的情況是當您有n:m關係時。但除非你要模擬galaxy collisions,否則你將不會有屬於多個GalaxyStarSystem