2015-09-11 159 views
0

我有場地,其中每個都有評論部分。每個評論都是一個Mongoose評論模式。每條評論都有一個創建者屬性,這是一個用戶模式。我正在嘗試查找特定用戶發佈的所有評論。我怎樣才能做到這一點?查詢Mongoose模式。嵌套評論

var VenueSchema = new mongoose.Schema({ 
    comments: [{ 
    type : mongoose.Schema.Types.ObjectId, 
    ref: 'Comment', 
    default: [] 
    }] 
}, 
{minimize: false}); 

var CommentSchema = new mongoose.Schema({ 
    creator: { 
    type: mongoose.Schema.Types.ObjectId, 
    ref: 'User' 
    } 
}, {minimize: false}); 


var UserSchema = new mongoose.Schema({ 
    token: String, 
    venues: [{ //in case we want users to save their favorite venues 
    type : mongoose.Schema.Types.ObjectId, 
    ref: 'Venue' 
    }] 
}); 

我已經試過

Venue.find({ 
    "comments.creator": "55f1fa1263877ed0067b78c0" 
    }, function(err, docs) { 
    console.log(docs); 
    res.send(docs); 
    }) 

但它返回一個空數組。 「55f1fa1263877ed0067b78c0」是樣本創建者_id。提前致謝!

回答

0

無法搜索creater其ID內Venue收藏因爲它只收集Comment ID。因此,爲了通過其ID進行搜索creater您需要更改如下圖所示:

var VenueSchema = new mongoose.Schema({ 
    comments: [CommentSchema] 
}, 
{minimize: false}); 

var CommentSchema = new mongoose.Schema({ 
    creator: { 
    type: mongoose.Schema.Types.ObjectId, 
    ref: 'User' 
    } 
}, {minimize: false}); 


var UserSchema = new mongoose.Schema({ 
    token: String, 
    venues: [{ //in case we want users to save their favorite venues 
    type : mongoose.Schema.Types.ObjectId, 
    ref: 'Venue' 
    }] 
}); 
0

由於venueSchema只存儲裁判的意見(這是註釋_id),您將無法使用場地模型來查詢評論。您可以將評論文件嵌入場地模式的評論數組中。

或者

使用註釋模型如下只需查詢該意見收集

Comment.find({ 
    "creator": "55f1fa1263877ed0067b78c0" 
    }, function(err, docs) { 
    console.log(docs); 
    res.send(docs); 
    })