2015-08-14 70 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,因爲它對我來說更容易實現和管理。無論如何感謝您的幫助! –