gpt4 book ai didi

javascript - MongoDB 最佳实践 - 一对多关系

转载 作者:行者123 更新时间:2023-12-02 10:56:52 25 4
gpt4 key购买 nike

根据这篇文章,我应该嵌入一个“引用”:MongoDB relationships: embed or reference?

用户.js

const mongoose = require('mongoose');

const Schema = mongoose.Schema;

const userSchema = new Schema({
email: {
type: String,
required: true
},
password: {
type: String,
required: true
},
createdEvents: ['Event']
});

module.exports = mongoose.model('User', userSchema);

Event.js

const mongoose = require('mongoose');

const Schema = mongoose.Schema;

const eventSchema = new Schema({
title: {
type: String,
required: true
},
description: {
type: String,
required: true
},
price: {
type: Number,
required: true
},
date: {
type: Date,
required: true
}
});

module.exports = mongoose.model('Event', eventSchema);

因此,嵌入事件在数据库中看起来像这样:

enter image description here

我的代码可以工作,但我很好奇这是否是嵌入事件的正确方法。因为一对多关系的每个示例都是通过引用创建的,而不是嵌入的。

最佳答案

根据我的经验,使用嵌入引用取决于我们处理的数据量。

在决定选择哪种方法时,您应该始终考虑:

1- 一对数:如果随着时间的推移,您将向用户添加少量事件,我建议您选择embedding方法,因为它更容易处理。

2-一对多:如果经常添加新事件,您完全应该选择referencing以避免将来出现性能问题。

为什么?

当您经常添加新的事件时,如果它们嵌入到用户文档中,该文档会随着时间的推移变得越来越大。将来您可能会面临 I/O 开销等问题。你可以在文章Why shouldn't I embed large arrays in my documents?中一睹大数组的弊端。 。尽管很难在任何地方找到它,但 MongoDB 中的大型数组被认为是性能反模式。

如果您决定引用,我建议您阅读Building with Patterns: The Bucket Pattern 。本文可以让您了解如何以非关系方式设计 user_events 集合。

关于javascript - MongoDB 最佳实践 - 一对多关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58505786/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com