繁体   English   中英

如何在 MongoDB 中从单独的集合中获取数据并将其与用户集合连接,而无需相同的公共 id 来链接它们?

[英]How to get data from a separate collection and join it with a user collection without having a same common id to link both of them in MongoDB?

我在 MongoDB 中有 2 个 collections,即“用户”和“词典”。 我正在构建一个简单的字典(简单的表格和表格),用户可以在其中存储他们学过的任何单词。 我还为 web 应用程序构建了身份验证,因此只有注册用户才能访问字典表。

我的问题是我不知道如何链接两个 collections,因为我没有共同的属性来查找 function。 我想做的基本上是每当用户登录时,他/她来自字典集合的数据将呈现在表中。

我是否需要在 collections 中创建一个公共属性/ID(那将是多余的吗?)?

用户和字典模式如下; (_id 应该在 collections 中自动创建,但我认为两个 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 种方式链接

  1. 您可以将用户 model 中对字典 model 的引用存储为引用数组。然后您将能够获取用户及其字典

dictionaries: [{ type: mongoose.Schema.ObjectId, ref: '<Name of Dictionary model>' }]

然后,您可以使用 populate 获取用户的字典

UserModel.find({}).populate('dictionaries').exec()

您可以在 mongoose 文档https://mongoosejs.com/docs/populate.html中找到示例

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

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

然后,您可以查询您的字典 model 以查找创建者

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

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

您有自己的答案,是的,您需要创建一个公共字段/id,这将帮助我们 map 每个用户到他们保存的单词。

如果您担心在 DB 中存储公共字段/id 两次,那么您可以使用类似如下的架构 go:

userSchema = {
  joindate:,
  fullname:,
  email:,
  password:,
  dateofbirth:
  dictionaries: [{
    word:,
    meaning:,
    example:,
    language:,
    date:,
  }]
}

users集合将具有dictionaries字段,您可以在其中推送该特定用户存储的所有单词。 而且你不需要做任何lookup 由于 MongoDB 是 NoSQL DB,因此根本没有关系。 你是一只自由的鸟。

更新:我所说的 common 字段是指usernameuserId类的东西。 我相信只有登录的用户才能存储单词。 然后,您可以获取登录用户的用户名,并将其与单词的其他详细信息一起存储在dictionaries集合中。 因此,更新后的 Schema 将如下所示:

const userSchema = mongoose.Schema({
  username: {
    type: String,
  },
  joindate: {
    type: Date,
  },
  fullname: {
    type: String,
  },
  email: {
    type: String,
  },
  password: {
    type: String,
  },
  dateofbirth: {
    type: Date,
  },
});

const dictionarySchema = mongoose.Schema({
  username: {
    type: String,
  },
  word: {
    type: String,
  },
  meaning: {
    type: String,
  },
  example: {
    type: String,
  },
  language: {
    type: String,
  },
  date: {
    type: Date,
  },
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM