node.js - Mongoose 多对多关系

标签 node.js mongodb express mongoose

我是 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/

相关文章:

json - 将json文件导入mongo的正确方法

node.js - NodeJs 重定向和 writeHead 的区别(303)

node.js - 找不到指定的模块 - Node oracledb

node.js - VS Code 自动 npm 构建失败并显示 "npm command not found"

javascript - 使用 gulp v4 重构的监视任务不起作用

node.js - npm install 任务启动时间太长

javascript - Node 中的单例 MongoDB 连接

node.js - Mongoose.js 在模式中存储未知对象

mysql - NodeJs MySQL 使用哈希密码登录

node.js - 另一个 Promise 问题 - 嵌套的 Sequelize 调用?