【问题标题】:Error while defining mongoose schemas定义猫鼬模式时出错
【发布时间】:2015-11-08 01:35:43
【问题描述】:

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

【问题讨论】:

    标签: node.js mongodb mongoose mean-stack


    【解决方案1】:

    您所拥有的是失败的,因为在 UserSchema 中使用 articleSchema 时未定义它。不幸的是,您可以颠倒定义模式的顺序,因为它们相互依赖。

    我实际上并没有尝试过,但是基于一些快速的谷歌搜索,有一种方法可以先创建架构,然后添加属性。

    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
    });
    

    【讨论】:

    • 我只使用了 ObjectIds,因为它更容易实现和管理。无论如何感谢您的帮助!
    猜你喜欢
    • 2018-01-21
    • 2017-11-20
    • 2021-08-19
    • 2013-09-22
    • 2020-05-18
    • 2021-01-25
    • 2020-06-24
    • 2016-08-05
    • 2016-09-02
    相关资源
    最近更新 更多