2011-12-05 27 views
5

例如,如果我有以下架構(爲了簡潔起見,大大簡化了)。我如何通過標籤搜索帖子?我知道如果標籤文檔集合被嵌入,但是我想讓Tag保留在他們自己的集合中,該怎麼做。搜索Mongoose中的嵌入對象

PostSchema = new Schema({ 
    title: String 
    body: String 
    tags: [{type: Schema.ObjectId, ref: 'Tag' }] 
}); 

TagSchema = new Schema({ 
    name: String 
}); 

// Here is what I've tried 
Post.find({'tags.name':'javascript'}) 
    .populate('tags') // Is it necessary to join the collections? 
    .run(function(err, posts) { 
     console.log('posts: ', posts); 
    }); 
+0

不應該是'Post.find({'tags.name':'javascript'})'在你的代碼? –

+0

是裏卡多。我試圖修剪掉那些無關緊要的東西,把錯誤的查詢放在那裏。感謝您致電 –

回答

3

是具有標籤的一個模式的最佳方法?像這樣簡單的東西應該工作:

Posts = new Schema({ 
    title: String 
    body: String 
    tags: [String] 
}) 

// ... 

Posts.find({ tags: { $in: ['javascript'] }, function(err, posts){ 
    console.log(posts) 
}) 
+0

在這種情況下,我認爲你的正確。我已經考慮到更接受的字符串數組方法..並使用這裏列出的mapreduced集合[鏈接](http://cookbook.mongodb.org/patterns/count_tags/)來獲得計數和獨特的標籤等。擺脫關係數據庫的思維定勢。 –

4

您應該可以使用object.field符號與貓鼬來查詢嵌入式文檔。但是,您可能需要確保嵌入式文檔將所有字段按順序聲明爲架構的一部分(在您的示例中,您在「comments.name」上查詢,但PostSchema沒有註釋字段) - 也許這是導致問題的原因? )

我能得到的概念這樣工作的證明,這應該成功運行爲-是:

var mongoose = require('mongoose') 
var Schema = mongoose.Schema 

mongoose.connect('mongodb://localhost/testjs'); 


PostSchema = new Schema({ 
    title: String, 
    body: String, 
    comments: [], 
    tags: [{type: Schema.ObjectId, ref: 'Tag' }] 
}); 

TagSchema = new Schema({ 
    name: String 
}); 


var Post = mongoose.model('Post', PostSchema); 

var mypost = new Post() 
mypost.title = "yo" 
mypost.body = "asfkjabfkjbsdf" 
mypost.comments = [{'name':'javascript', 'text':'sup'}] 
mypost.save(
    function(err){ 
    // Save the post, and then read it back by querying the embedded field 
    Post.find({'comments.name':'javascript'},function(err, posts){ 
     console.log('posts: ', posts); 
    }); 
    } 
); 
+0

我道歉我最初的代碼片段是海拉誤導。在我發佈之前,我已經嘗試了您的方法,但是如果您使用ObjectId的嵌入式數組而不是嵌入式文檔,則上述內容無效。 –