首页 > 解决方案 > 如何在猫鼬中引用另一个模型的字段

问题描述

我正在尝试根据用户名链接 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 架构中的字段,所以我想它应该类似于参考。

标签: javascriptmongodbexpressmongoose

解决方案


更新:好的,所以我读到猫鼬会为你做这件事。它可以根据您在架构中定义的 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 引用的文档进行第二次查询

  • 第一个写入速度较慢,但​​读取速度较快
  • 第二个写入速度更快,但读取速度较慢(对查询进行分页)

推荐阅读