簡體   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