我正在試驗我與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。我目前將它添加到數組中,但我不知道是否有更快/更容易的東西。我將不勝感激任何有關我的代碼的建議。
我注意到你沒有接受或評論我的答案呢。當我能夠幫助你時,請接受我的答案。當我無法幫助你時,請評論告訴我你需要的其他信息。 – Philipp