應該如何查詢某一筆記錄中「 comments」中的某一項呢?為什麼透過「_id」查詢不到呢?
{
"_id": "56fa1c5acb169bd213e485de",
"title": "ReactJS学习笔记",
"classify": "js",
"desc": "React是一个JavaScript库文件",
"author": "root",
"body": "",
"hidden": false,
"meta": {
"votes": 0,
"favs": 0
},
"date": "2016-03-30T08:20:36.866Z",
"comments": [
{
"body": "aaaa",
"date": "2016-03-30T08:43:50.401Z",
"guest": "A",
"email": "xxxxxx@qq.com",
"browser": "chrome",
"_id": "56fb91c6c4b8801709aec38a"
},
{
"_id": "56fb93ddc4b8801709aec38b",
"browser": "chrome",
"email": "xxxxxx@icloud.com",
"guest": "tester",
"date": "2016-03-30T08:52:45.445Z",
"body": "bbbbb"
}
],
"__v": 0
}
最直接的查詢:
然後回傳的物件裡面直接呼叫了 obj.comments.body
你查詢的_id是ObjectId類型,所以你也要用ObjectId類型的資料去查詢,而不是String類型的資料;
如果你用的是mongoose,試試這個方法,在查詢前,把你的string轉成ObjectId類型
完整的查詢: