2017-04-07 88 views
1

我是初學Node.JS和Mongoose的程序員。到目前爲止,我已經創建了一個非常簡單的博客與3個模型 - 文章,用戶,類別和一切工作正常。現在我想創建評論。因此,我希望每個用戶都能夠發表評論,並且每篇文章也能夠提供評論。我怎樣才能做到這一點,我怎麼能代表控制器邏輯來互相交流:貓鼬多對多關係

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

回答

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