javascript - 如何从单独的集合中获取数据并将其与用户集合连接,而无需在 MongoDB 中使用相同的公共 ID 来链接它们?
问题描述
我在 MongoDB 中有 2 个集合,即“用户”和“字典”。我正在构建一个简单的字典(简单的表格和表格),用户可以在其中存储他们学过的任何单词。我还为 Web 应用程序构建了身份验证,因此只有注册用户才能访问字典表。
我的问题是我不知道如何链接这两个集合,因为我没有共同的属性来执行查找功能。我想做的基本上是每当用户登录时,他/她来自字典集合的数据将呈现在表中。
我是否需要在两个集合中创建一个公共属性/ID(那将是多余的吗?)?
用户和字典模式如下;( _id 应该在两个集合中自动创建,但我认为两个 id 不一样)
const userSchema = mongoose.Schema({
joindate: {
type: Date,
},
fullname: {
type: String,
},
email: {
type: String,
},
password: {
type: String,
},
dateofbirth: {
type: Date,
},
});
const dictionarySchema = mongoose.Schema({
word: {
type: String,
},
meaning: {
type: String,
},
example: {
type: String,
},
language: {
type: String,
},
date: {
type: Date,
},
});
解决方案
您可以通过 2 种方式链接
- 您可以将 Dictionary 模型的引用存储在 User 模型中作为引用数组。然后您将能够获取用户及其字典
dictionaries: [{ type: mongoose.Schema.ObjectId, ref: '<Name of Dictionary model>' }]
然后,您可以使用 populate 获取用户的字典
UserModel.find({}).populate(‘dictionaries’).exec()
您可以在 mongoose 文档 https://mongoosejs.com/docs/populate.html中找到示例
- 您可以将 Dictionary 模型中的引用存储为新字段,例如。创造者
creator: { type: mongoose.Schema.ObjectId, ref: <Name of User Model> }
然后,您可以查询您的 Dictionary 模型以按创建者查找
DictionaryModel.find({creator: ObjectId(<ObjectId of User>)})
或者,如果您不想链接,您可以将字典直接存储为用户模型中的数组字段
推荐阅读
- android - 从 SQLite DB android 检索图像
- java - Dagger - 以最少的仪式注册没有@Inject 的课程
- grafana - 在 Grafana 的 Promql 查询中引用选择的时间范围(从、到)
- bash - 在 100+MB SQL 转储中插入三个块(SQL 行)
- extjs - ExtJS:如何使 tabreorderer 插件选项卡定位有状态
- c - STM32 CAN 通信 Rx 期间接收随机数据字节
- apache - 无法解决 htaccess 重写问题(对 seo 友好的 URL)
- ios - 如何确保字典中的所有键都已初始化
- haskell - 结合来自两个 Either Monad 的结果
- reactjs - 当我使用 Metro bundle 运行和测试应用程序时,它运行良好。但是当我构建 android apk 它无法正常工作时,它会再次重新启动