我的架构:
Account: mongoose.model('Account', new Schema({
account_name: String,
company: String,
notes: String,
contact_info: [this.ContactInfo]
})),
ContactInfo: mongoose.model('ContactInfo', new Schema({
name: String,
email: String,
phone: String,
notes: String
}))
当我尝试对contact_info执行任何操作时,它表示方法不存在。
var c = new ContactInfo...);
var a = new Account(...);
a.contact_info.create(c); //error, create doesn't exsit
a.contact_info.push(c); //works
a.contact_info.id(...).remove(); //id doesn't exist
我做错了吗?
我的完整代码在这里(不是太多):https://github.com/nycitt/node-survey-builder-api-server/blob/master/accounts.js
我正在接收来自Backbone.js的输入
答案 0 :(得分:1)
您的问题可能在schemas.js
之内。按文字定义对象时,this
不会引用正在定义的对象:
// ...
contact_info: [this.ContactInfo]
// ...
它将引用文字周围的上下文 - 在Node模块的情况下,exports
object - 没有ContactInfo
属性。所以,结果是:
// ...
contact_info: [undefined]
// ...
您仍然会有Array
,这就是push
可用的原因。但是,Mongoose不知道它是MongooseDocumentArray
,所以它不会有id
,create
等方法。
您必须在对象外定义模型以引用它们。还要注意顺序的变化:
var ContactInfo = mongoose.model('ContactInfo', new Schema({
// ...
});
var Account = mongoose.model('Account', new Schema({
// ...
contact_info: [ContactInfo]
});
module.exports = {
Account: Account,
ContactInfo: ContactInfo
};
或者,将它们附加到exports
,以便设置this.ContactInfo
(相同顺序):
exports.ContactInfo = ...;
exports.Account = ...;
答案 1 :(得分:0)
显然我做错了一些事情:
在Schemas中,引用其他Schemas NOT Models:
好:
var ContactInfoSchema = new Schema({
name: String
});
var AccountSchema = new Schema({
account_name: String,
contact_info: [ContactInfoSchema]
});
var ContactInfo = mongoose.model('ContactInfo', ContactInfoSchema);
var Account = mongoose.model('Account', AccountSchema);
为: var ContactInfoSchema = new Schema({ name:String, 电子邮件:String, 电话:字符串, 笔记:字符串 });
var AccountSchema = new Schema({
account_name: String,
contact_info: [ContactInfo] //subtle difference
});
var ContactInfo = mongoose.model('ContactInfo', ContactInfoSchema);
var Account = mongoose.model('Account', AccountSchema);
另一件事是做以下事情不保存任何东西!!!
account.contact_info.create(params);
account.save();
您还必须
var c = account.contact_info.create(params);
account.contact_info.push(c);
account.save();
对于那些感兴趣的人是我为Account和ContactInfo创建的CRUD方法。