我是 Node.JS 和 Mongoose 初学者。到目前为止,我已经创建了一个非常简单的博客,包含 3 个模型 - 文章、用户、类别,一切工作正常。现在我想创建评论。所以我希望每个用户都能够有很多评论,每一篇文章也都能够有很多评论。我该如何做到这一点以及如何在 Controller 中表示逻辑以相互交互:
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'}]
}
);
最佳答案
创建引用作者和文章的评论架构:
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() },
});
关于node.js - Mongoose 多对多关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43273804/