2016-11-30 69 views
0

我有2種型號:架構協會貓鼬

下面是用戶模型:

const userSchema = new mongoose.Schema({ 
    email: { type: String, unique: true, required: true }, 
    password: { type: String, required: true }, 
    passwordResetToken: String, 
    passwordResetExpires: Date, 

    facebook: String, 
    twitter: String, 
    tokens: Array, 

    profile: { 
    name: String, 
    gender: String, 
    location: String, 
    website: String, 
    picture: String 
    } 
}, { timestamps: true }); 

這裏是復活型號:

const reviveSchema = new mongoose.Schema({ 
    reviveShowName: {type: String, required: true}, 
    reviveTitle: {type: String, required: true}, 
    reviveCategory: {type: String, required: true}, 
    reviveGoal: {type: Number, required: true}, 
    revivePhoto: {type: String, required: true}, 
    reviveVideo: {type: String}, 
    reviveStory: {type: String}, 
    author: { 
     id: { 
     type: mongoose.Schema.Types.ObjectId, 
     ref: "User" 
     }, 
     name: String 
    } 
}, { timestamps: true }); 

在復活模式,我米試圖引用作者,並得到作者的ID和那個作品...我怎麼也得到配置文件的名稱 - >名稱...?很顯然name: String是錯誤的...

回答

3

貓鼬關係的工作,基於嵌套對象的reftype值。在您的情況下,您已將屬性author關聯到指向User模型。

如果你想填充author與用戶的信息,你應該只是做:

author: {  
    type: mongoose.Schema.Types.ObjectId, 
    ref: "User" 
} 

然後在你的查詢,你只需要使用填充

Revive.find({}) 
     .populate('author') 
     .exec(function(error, docs) { 
      console.log(docs); // will have `[{author:{profile:{...}}}]` data 
     });