一对多关系Mongo DB



学习来自Rails的Mongo DB,我在理解如何在我的两个模型之间建立连接时遇到了一些困难。

我有三种模式:网站、文章和用户(暂时不接触用户,只关注网站和文章(。

站点架构

const mongoose = require('mongoose')
const Schema = mongoose.Schema
const SiteSchema = new Schema({
name: {
type: String,
required: true
},
url: {
type: String,
required: true
},
articles: [{ type: Schema.Types.ObjectId, ref: 'article' }]
})
module.exports = mongoose.model('site', SiteSchema)

文章架构

const mongoose = require('mongoose')
const Schema = mongoose.Schema
const ArticleSchema = new Schema({
title: {
type: String,
required: true
},
author: {
type: String,
required: true
},
comments: {
type: Number,
required: true
},
source: [{ type: Schema.Types.ObjectId, ref: 'site' }]
})
module.exports = mongoose.model('article', ArticleSchema)

我在这里主要想建立的是,一个网站有很多文章,而一篇文章只来自一个来源(一个网站(。问题是我可以单独创建文章,并且可以在我的DB中创建网站->当我创建一个网站时,该网站在我的收藏中是这样的。

{
"articles": [],
"_id": "5f2dc9780897db6d6dea1f98",
"name": "New Site",
"url": "www.newsite.com",
"__v": 0
}

然而,当我试图创建一篇文章时,我很难理解如何在文章创建时将其与网站联系起来,我看到的是:

{
"source": [],
"_id": "5f2dca37358c7d74c23105aa",
"title": "pixel 5 !",
"author": "Ricky Rojas",
"comments": 10,
"__v": 0
}

我习惯于使用表来做这种事情,所以这让我有点困惑——我应该使用某种外键来识别文章的源id并分配它吗?这是位于我的/routes/articles.js文件夹中的帖子请求:

// @route POST /articles -> adds new instance of an article to the database
router.post('/', async (req, res) => {
const article = new Article({
title: req.body.title,
author: req.body.author,
comments: req.body.comments
// source: req.body.source,
})
try {
const newArticle = await article.save()
res.status(201).json(newArticle)
} catch (err) {
res.status(400).json({ message: err.message })
}
})

任何建议都有帮助!我想我的模式设置不正确。

您不需要将关系放在两者中,只需将其中一个放在中即可

如果经常从文章开始查询,则只在文章中放置关系,反之亦然。你说这篇文章只有一个站点,所以你不需要在关系中使用数组符号。以下是文章中关系的示例

const ArticleSchema = new Schema({
title: {
type: String,
required: true
},
author: {
type: String,
required: true
},
comments: {
type: Number,
required: true
},
source: { type: Schema.Types.ObjectId, ref: 'site' }
})

最新更新