我正在试验我与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