2015-08-14 100 views
0

我是mongo和猫鼬的新手。我正在尝试创建3个收藏集用户,文章和评论。我希望用户文档应该包含用户保存的文章。文章对象应该有用户和评论作为嵌入对象,评论应该嵌入用户对象。 我希望这可以通过使用单个对象的ID来完成,这样我可以减少加载时间,但是找不到使用猫鼬这样做的合适方法。请建议我应该如何继续进行Schema实施。定义猫鼬模式时出错

var UserSchema = new mongoose.Schema({ 
    name: String, 
    email: String, 
    profilePicture: String, 
    password: String, 
    readingList: [articleSchema] 
}); 

var commentsSchema = new mongoose.Schema({ 
    content: String, 
    votes:{ 
     up:[UserSchema], 
     down:[UserSchema] 
    }, 
    comments:[commentsSchema], 
    timestamp:Date.now 
}); 


var articleSchema = new mongoose.Schema({ 
    title: String, 
    content: String, 
    image: String, 
    votes:{ 
     up: [UserSchema], 
     down: [UserSchema] 
    }, 
    comments:[commentsSchema], 
    timestamp: Date.now 
}); 

回答

0

你有什么是失败,因为当你在UserSchema使用它articleSchema没有定义。不幸的是,你可以颠倒定义模式的顺序,因为它们相互依赖。

我还没有真正尝试过这种方式,但是基于一些快速的搜索功能,有一种方法可以先创建Schema,然后添加属性。

var UserSchema = new mongoose.Schema(); 
var CommentsSchema = new mongoose.Schema(); 
var ArticleSchema = new mongoose.Schema(); 

UserSchema.add({ 
    name: String, 
    email: String, 
    profilePicture: String, 
    password: String, 
    readingList: [ArticleSchema] 
}); 

CommentsSchema.add({ 
    content: String, 
    votes:{ 
     up:[UserSchema], 
     down:[UserSchema] 
    }, 
    comments:[CommentsSchema], 
    timestamp:Date.now 
}); 

ArticleSchema.add({ 
    title: String, 
    content: String, 
    image: String, 
    votes:{ 
     up: [UserSchema], 
     down: [UserSchema] 
    }, 
    comments:[CommentsSchema], 
    timestamp: Date.now 
}); 
+0

我刚刚使用了ObjectIds,因为它对我来说更容易实现和管理。无论如何感谢您的帮助! –