我已经定义了 2 个模式对象如下(用于 mongodb)
var User = describe('User', function () {
property('name', String);
property('email', String);
property('password', String);
set('restPath', pathTo.users);
});
var Message = describe('Message', function () {
property('userId', String, { index : true });
property('content', String);
property('timesent', Date, { default : Date });
property('channelid', String);
set('restPath', pathTo.messages);
});
Message.belongsTo(User, {as: 'author', foreignKey: 'userId'});
User.hasMany(Message, {as: 'messages', foreignKey: 'userId'});
但我无法访问相关的消息对象:
action(function show() {
this.title = 'User show';
var that = this;
this.user.messages.build({content:"bob"}).save(function(){
that.user.messages(function(err,message){
console.log('Messages:');
console.log(message);
});
});
// ... snip ...
}
});
尽管向消息集合添加了一条新消息,但消息数组始终为空。
我运行db.Message.find({userId:'517240bedd994bef27000001'})
了 mongo shell 并显示了您所期望的消息,所以我开始怀疑mongo 适配器是否存在问题。
CompoundJS 中的一对多关系显示了类似的问题(我认为)。
据我可以从文档中解决,这应该有效。我究竟做错了什么?
编辑:
在按照 Anatoliy 的建议将更改应用到我的架构后,我删除了我的 mongo 数据库并更新了 npm,但是当我尝试创建一个新用户时,我得到了以下信息:
Express
500 TypeError: Object #<Object> has no method 'trigger' in users controller during "create" action
at Object.AbstractClass._initProperties (/mnt/share/chatApp2/node_modules/jugglingdb/lib/model.js:123:10)
at Object.AbstractClass (/mnt/share/chatApp2/node_modules/jugglingdb/lib/model.js:31:10)
at Object.ModelConstructor (/mnt/share/chatApp2/node_modules/jugglingdb/lib/schema.js:193:23)
at Function.AbstractClass.create (/mnt/share/chatApp2/node_modules/jugglingdb/lib/model.js:222:15)
at Object.create (eval at (/mnt/share/chatApp2/node_modules/compound/node_modules/kontroller/lib/base.js:157:17), :16:10)....
EDIT2: 创建动作:
action(function create() {
User.create(req.body.User, function (err, user) {
respondTo(function (format) {
format.json(function () {
if (err) {
send({code: 500, error: user && user.errors || err});
} else {
send({code: 200, data: user.toObject()});
}
});
format.html(function () {
if (err) {
flash('error', 'User can not be created');
render('new', {
user: user,
title: 'New user'
});
} else {
flash('info', 'User created');
redirect(path_to.users);
}
});
});
});
});