javascript - 如何在猫鼬中引用另一个模型的字段
问题描述
我正在尝试根据用户名链接 Card 模式中 User 模型中的一些字段。所以例如这是我的卡片模式
const CardSchema = new mongoose.Schema({
text: {
type: String,
},
username: {
type: String,
ref: 'User',
required: true
},
userSticker: {
This is what I need to get from the user model based on the username or user id
}
这就是用户模型的样子:
const UserSchema = new mongoose.Schema({
username: {
type: String,
},
userSticker: {
type: String,
}
我需要的是在 Card 模式中始终拥有与具有该用户名的用户相同的 userSticker。在创建卡片时添加它是行不通的,因为 userSticker 可能会更改,并且我希望在发生这种情况时也更改 Card 架构中的字段,所以我想它应该类似于参考。
解决方案
更新:好的,所以我读到猫鼬会为你做这件事。它可以根据您在架构中定义的 ref 对您的表进行关系建模并填充关系数据。
检查此关系数据库设计到 mongoDB/mongoose 设计
本节适用于 MongoDB
这里有两个解决方案,因为 MongoDB 不是 SQL 之类的关系数据库。
第一个解决方案是在字段值更改时复制数据并更新所有字段
const CardSchema = new mongoose.Schema({
text: {
type: String,
},
username: {
type: String,
},
userSticker: {
type: String,
}
})
const UserSchema = new mongoose.Schema({
username: {
type: String,
},
userSticker: {
type: String,
}
})
然后每当 userSticker 更改时,您需要查询卡片集合并更新与用户名匹配的所有 userSticker
第二种解决方案是两个手动创建集合之间的引用
const CardSchema = new mongoose.Schema({
text: {
type: String,
},
user_id: {
type: String
}
})
const UserSchema = new mongoose.Schema({
_id: {
type: String,
},
username: {
type: String,
},
userSticker: {
type: String,
}
})
然后当您查询文档卡集合时,您可以对 user_id 引用的文档进行第二次查询
- 第一个写入速度较慢,但读取速度较快
- 第二个写入速度更快,但读取速度较慢(对查询进行分页)
推荐阅读
- python-3.x - 为什么ColumnTransformer中的Sklearn Transformer的构造函数被调用了两次,而且两次调用的参数不同
- c# - 加载 sqlite 扩展时,dotnet run 意外退出
- lua - 我怎样才能得到单词后面的所有文字
- python - 通过日期循环解决方案(Python 中 ORTools 的 CVRP 问题)
- python - python将多个json命令添加到json文件中
- javascript - 如何在 ReactJS 中为组件创建移动布局?
- entity-framework - 无法从链接表中获取数据
- node.js - 为什么我的护照中间件功能不能正常工作?
- php - Slim 应用程序错误 发生网站错误。, Slim 无法获取我的功能
- function - 使用“plot”命令时向量长度不一致