2017-11-30 11 views
0

私はmongooseを使用してアプリケーションを作成しようとしています。私はユーザースキーマを持っています。 。ユーザーのここでどのようにTwitterやInstagramの作業に似て、他のユーザー(ユーザースキーマ内でユーザースキーマを参照する(およびそのメソッドを使用してpopulateメソッドを使用する)? Mongoose

に従うことができます私の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' 
    } 
}) 

私は、彼らのように、ユーザーのフォロワーさんと、以下の情報を表示するルートを作成しようとしています。

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

しかし、返されるJSONは次のとおりです:

{ 
     "_id":"5a1dec7280a69b417a170e92", 
     "username":"vegeta", 
     "email":"[email protected]", 
     "__v":0, 
     "followers":[ 
     "5a1dec7280a69b417a170e92", 
     "5a1dedb9a88aad42cad87dde" 
     ], 
     "following":[ 
     "5a1dec7280a69b417a170e92", 
     "5a1dedb9a88aad42cad87dde" 
     ], 
     "password":"$2a$10$ZsEpC6LoE0I.FzsTtPo2IOBICRGoYsFV0s2RVNcCW/g9VO4ErGaKW" 
    } 
01名とidだから、私はこのような何かを試してみました

{ 
     "_id":"5a1dec7280a69b417a170e92", 
     "username":"vegeta", 
     "email":"[email protected]", 
     "__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方法を修正することができます:

代わりに、私は、フォロワーに関する情報など、以下のようなものを見たいのですが?

+0

スキーマを 'type:[Schema.Types.ObjectId]'から、ユーザー名とIDを持つカスタムタイプに編集します。 – Li357

答えて

0

SchemeはObject in 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' } 
    }] 
}) 

は詳細についてはMongoose Schema Typesを参照してください。お役に立てれば。

+0

フォロー:[{ _id:{タイプ: '文字列'}、 ユーザー名:{タイプ: '文字列'} }]のようなものと比較して、 – mdash1

+0

私の答えにコードを使用すると、あなたはmongo ** _ id **をフロントエンドに公開することはなく、一意である** username **を代わりに使用するので、より安全です。 –

+0

また、以下のフォロワーの下で_idをキーとして使用することはできません –

関連する問題