2016-11-23 79 views
0

我定義這樣貓鼬找到的ObjectId

var accountPostSchema = new mongoose.Schema({ 
    account: { 
    id: { type: mongoose.Schema.Types.ObjectId, ref: 'Account' } 
    }, 
    post: { 
    id: { type: mongoose.Schema.Types.ObjectId, ref: 'Post' } 
    } 
}); 

app.db.model('AccountPost', accountPostSchema); 

貓鼬架構當用戶(賬戶持有人)創建一個帖子,我保存在後的模式後,並獲得了「帖子ID」。然後,我保存了「帖子ID」,並在上面accountPostSchema的「帳戶ID」 這樣

var fieldsToSet = { 
    post: { 
    id: postId 
    }, 
    account: { 
    id: accountId 
    } 
}; 

db.models.AccountPost.create(fieldsToSet, function(err, accountPost) { 
    if (err) { 
    // handle error 
    } 

    // handle success 
}); 

進入幾個帖子ID的經過和帳戶ID的,我看到了下面的結果在蒙戈外殼

> db.accountposts.find({}) 
{ "_id" : ObjectId("5835096d63efc04da96eb71e"), "post" : { "id" : ObjectId("5835096d63efc04da96eb71d") }, "account" : { "id" : ObjectId("5833c920c868d7264111da69") }, "__v" : 0 } 
{ "_id" : ObjectId("583509e12052c7a2a93c4027"), "post" : { "id" : ObjectId("583509e12052c7a2a93c4026") }, "account" : { "id" : ObjectId("5833c920c868d7264111da69") }, "__v" : 0 } 

現在我如何找到所有匹配的'職位'給出一個accountId? (不是帖子ID的)

例如,如果我的帳戶ID 583509e12052c7a2a93c4026,我需要找到帖子Post._id = 5835096d63efc04da96eb71d和Post._id = 583509e12052c7a2a93c4026

什麼是我應該運行,以獲得匹配查詢帖子?

回答

1

我認爲,你應該按照這種方式來獲得與特定accountid相關的所有帖子。

db.accountposts.find({'account.id' : accountId}) 
.populate('post.id') 
.exec(); 
+0

謝謝!這工作 – Rahal

+0

歡迎您。 :D –

1

首先,我建議改變你的架構下面

var accountPostSchema = new mongoose.Schema({ 
    account: { 
    type: mongoose.Schema.Types.ObjectId, 
    ref: 'Account' 
    }, 
    post: { 
    type: mongoose.Schema.Types.ObjectId, 
    ref: 'Post' 
    } 
}); 

這實際上更有意義,尤其是當你嘗試填充子文檔。其實,我會說這個Schema是無用的。你爲什麼不定義你的Post架構如下?

var PostSchema = new mongoose.Schema({ 
    poster: { 
    type: mongoose.Schema.Types.ObjectId, 
    ref: 'Account' 
    }, 
    message: String 
}); 

如果使用後者的代碼,你可以執行以下查詢特定用戶獲得的所有帖子:一旦你嘗試

db.posts.find({poster: accountId}, function(dbErr, userPosts) { 
    if(dbErr) { 
    // Handle the error. 
    } 

    // Do something with the posts by accountId in the array userPosts. 
}); 

poster去除id領域的優勢變得清晰填充poster。如果你定義poster與現場id對象,並嘗試填充它,你將需要訪問有關海報數據,例如:

posterName = retrievedPost.poster.id.name; 

或者,只是使poster領域的ObjectId直接,你可以更直接地訪問填充的用戶:

posterName = retrievedPost.poster.name; 
+0

你的模式更有意義。我應該改變這一點。感謝您的建議。 – Rahal