簡體   English   中英

如何從貓鼬中的另一個模型引用字段

[英]How can I reference a field from another model in mongoose

我正在嘗試根據用戶名鏈接 Card 架構中用戶模型中的一些字段。 例如,這是我的 Card 架構

 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 可能會發生變化,我希望在發生這種情況時卡片架構中的字段也發生變化,所以我想它應該是一個參考。

更新:好的,我已經讀到貓鼬為你做這件事。 它可以對您的表進行關系建模,並根據您在架構中定義的引用來填充關系數據。

查看關系數據庫設計到 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 引用的證件進行第二次查詢

  • 第一個寫入速度較慢,但​​讀取速度較快
  • 第二個寫入速度更快但讀取速度更慢(對查詢進行分頁)

來自官方貓鼬文檔查詢人口

 const cardSchema = new mongoose.Schema({
      text: {
        type: String,
      },
      username: {
       type: String,
       ref: 'User',
       required: true
      },
      userSticker: {
       type: Schema.Types.ObjectId, 
       ref: 'User'
      }
};

const userSchema = new mongoose.Schema({
  username: {
    type: String,
  },
  userSticker: {
   type: String,
  }
}

const User = mongoose.model('User', userSchema);
const Card = mongoose.model('Card', cardSchema);

Card.findbyId(id).populate('userSticker', 'userSticker').exec(function(err, card) {/* Do stuff... */})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM