定义mongoose模式时出错

时间:2015-08-14 17:59:38

标签: node.js mongodb mongoose mean-stack

我是mongo和mongoose的新手。我正在尝试创建3个集合用户,文章和评论。我希望用户文档应包含用户已保存的文章。 articles对象应该具有用户和注释作为嵌入对象,注释应该具有嵌入的用户对象。 我希望使用单个对象的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
});

1 个答案:

答案 0 :(得分:0)

您所拥有的内容失败,因为articleSchema未在UserSchema中使用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 }); 时定义。不幸的是,您可以颠倒定义模式的顺序,因为它们相互依赖。

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

def saveGroup(group_buffer)
    ids = []
    self.transaction do
        group_buffer.each do |i|
         i.save
         ids << i.id
        end
    end
 if ids.empty?
  false
 else
  ids
 end
end