我对猫鼬和猫鼬很陌生。我试图创建3个集合用户,文章和评论。我希望用户文档应该包含用户保存的文章。文章对象应该有用户和评论作为嵌入对象,评论应该有嵌入的用户对象。我希望使用单个对象的id来完成这一点,这样我就可以减少加载时间,但无法找到使用mongoose的合适方法。请建议我应该如何继续与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
});
你所拥有的是失败的,因为当你在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
});