2016-09-28 5 views
0

私はこれに関するいくつかの答えを読んできましたが、まだそれを動作させることはできません。Populateは参照オブジェクト全体を取得しません

私のモデルオブジェクトは深くネストされておらず、非常に簡単です。これは、参加しているユーザーのリストと、参加したイベントのリストを持つユーザーを持つイベントです。

let DinnerSchema = new mongoose.Schema({ 
    date: { 
    type: Date, 
    unique: true, 
    timestamps: true, 
    required: true 
    }, 
    title:{type: String, require: true}, 
    attending: [{ 
    type: mongoose.Schema.Types.ObjectId, 
    ref: 'User' 
    }] 
}) 

やユーザー:

let UserSchema = new mongoose.Schema({ 
    email: { 
    type: String, 
    lowercase: true, 
    unique: true, 
    required: true 
    }, 
    name:{ type: String, require: true }, 
    password: {type: String ,required: true}, 
    dinners: [{ 
    type: mongoose.Schema.Types.ObjectId, 
    ref: 'Dinner' 
    }] 
}) 

かつ明快にするためにここに移入を使用しています全体のルートがあります。そうのような

userpage.get('/', authCheck, (req, res) => { 
    const options = { _id: '57ebbf48bd6914036f99acc7' } 
    return Dinner 
    .findOne(options) 
    .populate('User', 'name') //I'VE TRIED ADDING 'name' BASED ON SOME ANSWERS I SAW 
    .exec((err, newDinner) => { 
    if (err) { 
     console.log(err) 
     res.status(400).end() 
    } 
    console.log(newDinner) // SHOW'S USERS ID'S BUT NO OTHER FIELDS 
    return res.json({ 
     sucsess: true, 
     data: newDinner 
     }) 
    }) 
}) 

私はデータベース自体に正しく理解していればのみがすべき他のモデルへの参照であり、実際にはそのフィールドのすべてではなく、結合は入力と一緒に行われます。私のdb構造体ショーはちょうどリファレンスなので、大丈夫です。

私の後ろにあるフィールドの名前(この場合は名前フィールド)を指定しようとしましたが、これは機能しませんでした。

マイ人口の結果は常に次のように見え、_id 1を除く任意の他のフィールドを表示しません:私はここで

{ 
_id: 57ebbf48bd6914036f99acc7, 
    date: 2016-09-27T22:00:00.000Z, 
    title: '1', 
    __v: 0, 
    attending: [ 57ebbcf02c39997f9cf26891, 57ebbdee098d3c0163db9905 ] 
} 

何を台無しですか?

答えて

1

におけるユーザーの参照が4つのパラメータを受け取ります。 ({制限:10}など)

  1. パス
  2. 選択(フィールドが復帰されるように)、
  3. 条件
  4. オプション

あなたのケースでは、あなたがに正しい道を渡していません人口が多い。

userpage.get('/', authCheck, (req, res) => { 
    const options = { _id: '57ebbf48bd6914036f99acc7' } 
    return Dinner 
    .findOne(options) 
    .populate('attending', 'name') 
    .exec((err, newDinner) => { 
    if (err) { 
     console.log(err) 
     res.status(400).end() 
    } 
    console.log(newDinner) // SHOW'S USERS ID'S BUT NO OTHER FIELDS 
    return res.json({ 
     sucsess: true, 
     data: newDinner 
     }) 
    }) 
}) 

これで、出席ユーザーの名前がす​​べて返されます。

1

あなたはattendingを移入する必要がある - それは、マングースの移入で夕食スキーマ

関連する問題