2015-07-28 70 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