1

我的架构:

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 的输入

4

2 回答 2

1

所以显然我做错了一些事情:

在 Schemas 中,引用其他 Schemas NOT 模型:

好的:

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, email: String, phone: String, notes: 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 方法。

https://github.com/nycitt/node-survey-builder-api-server/blob/f94fcd4b05bf0af4f34a0e00f4ff79ebf64e24e1/accounts.js

于 2012-12-19T19:04:45.813 回答
1

您的问题可能在schemas.js. 通过字面量定义对象时,this不会引用正在定义的对象:

// ...
    contact_info: [this.ContactInfo]
// ...

相反,它将引用文字周围的上下文——在节点模块的情况下,exports对象——没有ContactInfo属性。所以,结果是:

// ...
    contact_info: [undefined]
// ...

你仍然会有一个Array,这就是为什么push可用。但是,Mongoose 不知道将其设为 a 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 = ...;
于 2012-12-19T17:06:00.303 回答