2016-09-21 48 views
0

我有一個商店對象,我從mongodb檢索到, 我有興趣使用值store.comments。節點js返回undefined從mongodb obejct內部值

我登錄商店價值,它是:

store:{ _id: 57e246f73e63d635cce3d174, 
    __v: 0, 
    comments: 57e246f73e63d635cce3d177, 
    loc: [ 105.832321, 105.233272 ], 
    name: '24 store', 
    reportedFalse: [], 
    products: [], 
    currentRanking: 
    { likes: 57e246f73e63d635cce3d175, 
    dislikes: 57e246f73e63d635cce3d176 }, 
    timePosted: Wed Sep 21 2016 11:38:15 GMT+0300 (Jerusalem Summer Time) }, 

然後我登錄的對象意見值的價值 - result.comments

store comments objectid: undefined 

,似乎當我嘗試稍後由評論值搜索它沒有成功用它進行搜索。因爲搜索返回null,雖然我看到在我的分貝我有在用相同的ID「意見」表/架構相應的對象....

Comments.findById(commentsId,function(commentsErr,commentsArrObj){ 
... 
cb(null, commentsArrObj._id); 
        } 

我得到:

TypeError: Cannot read property '_id' of null 

參考我的架構的繼承人部分:

 name: String, 
     comments: mongoose.Schema.Types.ObjectId, // each comment has a object id - responder, link curl? crud? to his profile, profile pic, date time. 
     timePosted : { type: Date, default: Date.now }, 
     currentRanking: { 
      likes: mongoose.Schema.Types.ObjectId, // a votes document 
      dislikes: mongoose.Schema.Types.ObjectId // a votes document 
     }, 
+0

'comments'是** ObjectId **,所以你不能訪問'comments._id' – tmquang6805

+0

嗨,謝謝。第二個查詢是相當愚蠢的我真的搜索一個對象,並返回其_id,它應該仍然工作...我認爲這是我提到的第一件事,我無法訪問result.comments –

回答

1

在您的模式,你必須使用「參考」

comments: mongoose.Schema.Types.ObjectId,ref:'comments'(modal name of comments) 

引用評論模式並使用填充評論來獲取評論數據。

+0

謝謝,生病嘗試一下。一旦我擁有參考資料,我可以在什麼查詢中訪問實際的對象?可以說,store.comments擁有參考...非常感謝。虐待也閱讀。 –

0

控制錯誤對象「commentsErr」,然後檢查它打印的內容。如果您的commentsId類型更改爲字符串,則可能是不從模式查找註釋的可能原因。嘗試將其轉換爲ObjectId。

使用:

Comments.findById(new mongoose.Types.ObjectId(id),function(commentsErr,commentsArrObj){ 
      cb(null, commentsArrObj._id); 
}) 

建議:用貓鼬填充使用裁判,讓你不用找單獨的查詢獲得評論記錄。