猫鼬有许多关系

时间:2017-04-07 08:53:21

标签: node.js mongodb express mongoose

我是Node.JS和Mongoose程序员的初学者。到目前为止,我创建了一个非常简单的博客,包含3个模型 - 文章,用户,类别,一切正常。现在我想创建评论。所以我希望每个用户都能够有manny评论,每篇文章也能够有manny评论。我该怎么做?如何在控制器中表示逻辑以相互交互:

let articleSchema = mongoose.Schema (
{
    author: {type: ObjectId, ref: 'User'},
    title: {type: String, required: true },
    content: {type: String, required: true },
    category: {type: ObjectId, ref: 'Category', required: true},
    date: {type: Date, default: Date.now() },
}
);

let userSchema = mongoose.Schema(
{
    email: {type: String, required: true, unique: true},
    passwordHash: {type: String, required: true},
    fullName: {type: String, required: true},
    salt: {type: String, required: true},
    articles: [{type: ObjectId, ref: 'Article'}],
    roles: [{type: ObjectId, ref: 'Role'}]
}
);

let categorySchema = mongoose.Schema (
{
    name: {type: String, required:true},
    articles: [{type: ObjectId, ref: 'Article'}]
}
); 

1 个答案:

答案 0 :(得分:2)

创建将引用作者和文章的评论模式:

let commenSchema = mongoose.Schema (
{
    author: {type: ObjectId, ref: 'User', required: true},
    content: {type: String, required: true },
    article: {type: ObjectId, ref: 'Article', required: true},
    date: {type: Date, default: Date.now() },
});