2016-08-05 70 views
0

我正在開發移動應用的REST API設置的介紹,這是我使用貓鼬 - 外鍵參考

var UserSchema = new Schema(
{ 
    email : 
    { 
     type : String, 
     unique : true 
    }, 
    login_type : String, 
    username : 
    { 
     type : String, 
     index : true 
    }, 
    password : String 
} 

模型的一部分,我加了用戶的OID發佈模式作爲參考

var PostSchema = new Schema(
{ 
    author : {type : Schema.Types.ObjectId, ref : "User"}, 
    board_id : {type : Schema.Types.ObjectId, ref : "Board"}, 
    regDate : Number, 
    lastModDate : Number, 
    title : String, 
    content : String, 
} 

所以,帖子可以引用用戶集合來獲得發佈它的用戶的username。所以我想獲得用戶的用戶名,其他人沒有必要。 爲此,我使用以下。

var query = Post.find({"regDate" :{$lte : before}}, 
{ 
    _id : 1, 
    title : 1, 
    "author.username" : 1, 
    regDate : 1 
}) 

但是貓鼬忽略了那"author.username"。我怎樣才能得到author的用戶名,不是全部?

回答

1

您應該使用populate功能,並列舉選定字段有:

Post 
    .find({ regDate :{ $lte : before }}, 'title reqDate') 
    .populate('author', 'username') 
    .exec();