2016-09-28 59 views
0

我一直在閱讀關於這個問題的一些答案,但我仍然無法讓它工作。填充不檢索整個引用的對象只是ID

我的模型對象沒有深度嵌套,而且非常簡單。這是具有參與其中的用戶列表的事件以及具有他們參加的活動列表的用戶列表。像這樣:

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一個任何其他領域:

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

什麼我搞砸了這裏?

回答

1

在貓鼬填入接收4個參數的用戶參考。

  1. 路徑
  2. 選定的區域(以回報),
  3. 條件
  4. 選項(如{限制:10})

你的情況,你是不是傳遞給正確的道路填充。它應該是

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 - 這是在晚宴模式