2017-02-02 116 views
0

林2個獨立的蒙戈文件獲取信息,我有貓鼬(V4.0.1)工作區模式:使用MongoDB的一個貓鼬查詢

var Workspace = new mongoose.Schema({ 
    name: { 
    type: String, 
    required: true 
    }, 
    userId: { 
    type: String, 
    required: true 
    }, 
    createdOn: { 
    type: Date, 
    "default": Date.now 
    } 
}); 

和用戶模式:

var User = new mongoose.Schema({ 
    email: { 
    type: String, 
    required: true, 
    unique: true 
    }, 
    organisation: { 
    type: String, 
    required: true 
    }, 
    location: { 
    type: String, 
    required: true 
    }, 
    verifyString: { 
    type: String 
    }, 
    verified: { 
    type: Boolean, 
    default: false 
    }, 
    password: { 
    type: String, 
    required: true 
    }, 
    createdOn: { 
    type: Date, 
    "default": Date.now 
    }, 
    isAdmin: { 
    type: Boolean, 
    default: false 
    } 
}); 

所以Workspace userIdUser文件中的ObjectID

當Im以管理員身份登錄時,我想獲取所有工作區以及擁有該工作區的用戶的電子郵件。

什麼Im做越來越很雜亂:

Workspace.find({}).exec.then(function(workspaceObects){ 

    var userPromise = workspaceObects.map(function(workspaceObect){ 
     // get the user model with workspaceObect.userId here 
    }); 

    // somehow combine workspaceObjects and users 

});

上述不工作,變得非常混亂。基本上我必須遍歷workspaceObjects並從工作區userId中檢索用戶對象。但是,因爲它的所有承諾,它變得非常複雜,容易犯錯誤。

有沒有更簡單的方法來做到這一點?在SQL中,它需要一個簡單的連接。我的模式錯了嗎?我可以在一個Mongoose查詢中獲得所有工作區及其用戶所有者的電子郵件嗎?

回答

2
var Workspace = new mongoose.Schema({ 
    userId: { 
    type: String, 
    required: true, 
    ref: 'User' //add this to your schema 
    } 
}); 

Workspace.find().populate('userId').exec((err, res) => { 
    //you will have res with all user fields 
}); 

http://mongoosejs.com/docs/populate.html

+0

非常簡單謝謝! – Mark

+0

np。如果你想加入沒有貓鼬,請參閱mongoDB中的「lookup aggregation operator」,https://docs.mongodb.com/manual/reference/operator/aggregation/lookup/ – Jackson

1

蒙戈沒有加入,但貓鼬提供了一個非常強大的工具來幫助你,你必須改變模型一點點,使用填入: Mongoose population

你有對模型進行一些更改並在工作空間模型中獲取用戶模型的信息。

希望它有幫助

+0

謝謝,我現在使用填充方法並且已經改變了模式,效果很好 – Mark