首页 > 解决方案 > 如何从单独的集合中获取数据并将其与用户集合连接,而无需在 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,
  },
});

标签: javascriptmongodbexpressmongoose

解决方案


您可以通过 2 种方式链接

  1. 您可以将 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中找到示例

  1. 您可以将 Dictionary 模型中的引用存储为新字段,例如。创造者

creator: { type: mongoose.Schema.ObjectId, ref: <Name of User Model> }

然后,您可以查询您的 Dictionary 模型以按创建者查找

DictionaryModel.find({creator: ObjectId(<ObjectId of User>)})

或者,如果您不想链接,您可以将字典直接存储为用户模型中的数组字段


推荐阅读