如何在基本情况下使用骨干网和mongoDB模式正确管理集合
问题描述:
我尝试了两种不同的方式来管理集合,第二种听起来比较干净,但我无法使其工作。如何在基本情况下使用骨干网和mongoDB模式正确管理集合
我来这里知道了什么是组织对这个非常基本的情况您的骨干和MongoDB架构代码(为什么第二个不工作)
在我的这两个例子,这种情况最好的办法是一个Model User
第一示例中的collection Friends
(工作良好)
客户端侧
App.Models.User = Backbone.Model.extend({
defaults : {
username : "example",
Friends: []
},
});
服务器端
UserSchema : {
name: {
type: String,
required: true,
unique: true
},
Friends:
[ {
user_id: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
},
status: {
type: Boolean
},
}]
用这种方法,当我从User document
填充Friends references
,骨干得到很好的集合时,我从客户端获取它。
第二个例子(好像吸尘器给我,但无法获取集合时)
客户端
App.Models.User = Backbone.Model.extend({
defaults : {
username : "example",
status: [], //Since Friends is now a collection i build an array to index each user_id according to its status.
Friends: new App.Collections.User()
},
});
服务器端
UserSchema : {
name: {
type: String,
required: true,
unique: true
},
status: [ {
user_id: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
},
value: Bolean
} ],
Friends:
[ {
user_id: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
}
}]
App.Collections 。用户
App.Collections.User = Backbone.Collection.extend({
model: App.Models.User,
initialize : function() {
},
getFriends: function(callback) {
console.log('getFriends called!');
this.url = App.url+'friends';
this.fetch({
success: function(collection, response, options) {
console.log('fetch OK');
console.log(collection.toJSON());
callback(true);
},
error: function(collection, response, options) {
console.log('fetch KO');
callback(false);
}
});
}
});
用这种方法,当我取Friends collection
,我得到一个错误Uncaught TypeError: undefined is not a function (on chrome)
或TypeError: this.model is not a constructor (on firebug)
,无论在backbone-0.9.9.js (ligne 26)
碰巧刚刚从collection's fetch
方法,只有当作为success callback
内前有一个从服务器ide返回的集合(当它为空时没有问题,就像骨干不能解析它一样)。
的JSON返回的模样:
[
{
"__v": 0,
"_id": "5137cdf1538238073f000005",
"username": "Someone Else",
"status": [
{
"user_id": "5137cb9b730754a666000006",
value: true
}
],
"Friends": [
{
"user_id": "5137cb9b730754a666000006",
"_id": "5137cf2e0399fd7c3f000005"
}
],
},
"_id": "5137cf2e0399fd7c3f000006"
}
]
那么,什么是组织这次两法之间的代码的最佳方式是什么?为什么你认为我得到这个错误与第二个(是我的JSON无效?)?
向我们展示你的App.Collections代码。用户 – glortho 2013-03-07 01:03:05
@glortho我刚刚添加了它,'console.log('getFriends called!');'启动并且错误出现在后面。 – Ludo 2013-03-07 01:18:18