【发布时间】:2015-04-11 20:32:01
【问题描述】:
我正在试验 MEAN 堆栈,特别是 MEAN.js。
虽然文档中对所有内容都进行了很好的解释,但似乎文档或示例中并未解释将实体(或模型)与另一个实体(或模型)相关联的简单任务。
例如,很容易为 Ideas 生成一个 crud,为 Polls 生成一个 crud。但是,如果我必须以一对多的关系将“民意调查”链接到“想法”怎么办?
我假设我会在 polls.client.controller.js 中做类似的事情:
// Create new Poll
$scope.create = function() {
// Create new Poll object
var poll = new Polls ({
ideaId: this.idea.ideaId,//here I associate a poll with an Idea
vote1: this.vote1,
vote2: this.vote2,
vote3: this.vote3,
vote4: this.vote4,
vote5: this.vote5
});
// Redirect after save
poll.$save(function(response) {
$location.path('polls/' + response._id);
// Clear form fields
$scope.name = '';
}, function(errorResponse) {
$scope.error = errorResponse.data.message;
});
};
但是当 Angular 模型被推送到 Express.js 后端时,我在请求中看不到任何关于 Idea 的痕迹,我得到的唯一东西就是 Poll。
/**
* Create a Poll
*/
exports.create = function(req, res) {
var poll = new Poll(req.body);
poll.user = req.user;
//poll.ideaId = req.ideaId;//undefined
poll.save(function(err) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.jsonp(poll);
}
});
};
这是我的猫鼬模型:
'use strict';
/**
* Module dependencies.
*/
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
/**
* Poll Schema
*/
var PollSchema = new Schema({
vote1: {
type: Number
},
vote2: {
type: Number
},
vote3: {
type: Number
},
vote4: {
type: Number
},
vote5: {
type: Number
},
created: {
type: Date,
default: Date.now
},
user: {
type: Schema.ObjectId,
ref: 'User'
},
idea: {
type: Schema.ObjectId,
ref: 'Idea'
}
});
mongoose.model('Poll', PollSchema);
我确信我做错了什么,但任何关于如何执行此任务的解释(或链接)超出我的这个特定错误或设置将不胜感激。
【问题讨论】:
标签: angularjs mongodb express mongoose mean