簡體   English   中英

在用戶架構中引用用戶架構(並在其中使用populate方法)? 貓鼬

[英]Referencing User Schema inside a User schema (and using the populate method with it)? Mongoose

我正在嘗試使用貓鼬創建一個應用程序。 我有一個用戶架構。 用戶可以關注其他用戶(類似於Twitter或Instagram的工作方式。

這是我的UserSchema:

let UserSchema = new Schema({
    email: {
        type: String,
        required: true,
        unique: true,
    },
    username: {
        type: String,
        required: true,
        unique: true,
    },
    password: {
        type: String
    },
    following: {
        type: [Schema.Types.ObjectId],
        ref: 'User'
    },
    followers: {
        type: [Schema.Types.ObjectId],
        ref: 'User'
    }
})

我正在嘗試創建一條路線,以顯示用戶的關注者的和關注的信息,例如其名稱和ID。 所以,我嘗試了這樣的事情:

User.findOne({ _id: req.session.user }).populate('follower',['username']).then((user) => {
        res.send(user);
    })

但是,返回的json是:

   {
      "_id":"5a1dec7280a69b417a170e92",
      "username":"vegeta",
      "email":"vegeta@gmail.com",
      "__v":0,
      "followers":[
         "5a1dec7280a69b417a170e92",
         "5a1dedb9a88aad42cad87dde"
      ],
      "following":[
         "5a1dec7280a69b417a170e92",
         "5a1dedb9a88aad42cad87dde"
      ],
      "password":"$2a$10$ZsEpC6LoE0I.FzsTtPo2IOBICRGoYsFV0s2RVNcCW/g9VO4ErGaKW"
   }

相反,我想查看有關關注者的信息,並關注以下信息:

   {
      "_id":"5a1dec7280a69b417a170e92",
      "username":"vegeta",
      "email":"vegeta@gmail.com",
      "__v":0,
      "followers":[
         {
            _id: "5a1dec7280a69b417a170e92",
            username: "vegeta"
         },
         {
            _id: "5a1dedb9a88aad42cad87dde",
            username: "goku"
         }
      ],
      "following":[
         {
            _id: "5a1dec7280a69b417a170e92",
            username: "vegeta"
         },
         {
            _id: "5a1dedb9a88aad42cad87dde",
            username: "goku"
         }
      ],
      "password":"$2a$10$ZsEpC6LoE0I.FzsTtPo2IOBICRGoYsFV0s2RVNcCW/g9VO4ErGaKW"
   }

如何修復User.findOne方法來解決我的問題?

可以如下更改架構以使其工作,因為我們可以在Scheme中使用對象。

let UserSchema = new Schema({
  email: { type: String, required: true, unique: true },
  username: { type: String, required: true, unique: true },
  password: { type: String },
  following: [{ 
    _id: { type: [Schema.Types.ObjectId], ref: 'User' },
    username: { type: String,  ref: 'User' } 
  }],
  followers: [{ 
    _id: { type: [Schema.Types.ObjectId], ref: 'User' },
    username: { type: String,  ref: 'User' }
  }]
})

有關更多詳細信息,請參閱貓鼬模式類型 希望這可以幫助。

暫無
暫無

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

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