Mongoose id函数返回null

时间:2015-05-15 17:28:25

标签: node.js mongodb mongoose

我正在尝试从MongoDB获取子文档。我可以获得父文档,如下所示:

    {
        "_id" : ObjectId("5550a7948be994430f7df1b4"),
        "address" : "Grafton St, Dublin 2",
        "coords" : [
            -6.2597468,
            53.3422998
        ],
        "facilities" : [
            "food",
            "irish history"
        ],
        "name" : "Laura Dunphy",
        "openingTimes" : [
            {
                "days" : "Monday - Friday",
                "times" : [
                    "10am",
                    "12pm",
                    "2pm"
                ]
            },
            {
                "days" : "Saturday",
                "times" : [
                    "8am",
                    "10am",
                    "12pm"
                ]
            }
        ],
        "rating" : 3,
        "reviews" : [
            {
                "author" : "Simon Holmes",
                "id" : ObjectId("5550c26e8c334adebc7c5dc3"),
                "rating" : 5,
                "timestamp" : ISODate("2013-07-15T23:00:00Z"),
                "reviewText" : "Great guide, it was fun."
            }
        ]
    }

当我这样做时:

console.log('guide.reviews is ');
console.log(guide.reviews);

我明白了:

guide.reviews is 
 [{ id: 5550c26e8c334adebc7c5dc3,
  rating: 5,
  timestamp: Tue Jul 16 2013 00:00:00 GMT+0100 (IST),
  reviewText: 'Great guide, it was fun.',
  createdOn: Fri May 15 2015 18:20:57 GMT+0100 (IST),
  author: 'Simon Holmes' }]

哪个好。但是当我尝试使用Mongoose id函数进行审核时,我总是回到null:

review = guide.reviews.id('5550c26e8c334adebc7c5dc3');

console.log('review is ');
console.log(review);

结果:

review is
null

知道我做错了吗?

2 个答案:

答案 0 :(得分:2)

MongooseDocumentArray.id(id)方法在文档数组中搜索result = regexp(str,'(?<=(".*").*),', 'split'); 属性,但您的子文档没有_id属性,而是_id。您必须将其更改为id,或使用普通的_id或类似的解决方法。

答案 1 :(得分:0)

我可能错了,但我以前从未见过Mongoose中的那种API。

document.id存在,但它是一个返回_id字段的字符串化版本的函数。

在你的情况下,你可以通过循环浏览列表并选择你想要的那个。

var review = false
for (var i = 0; i < guide.reviews.length; i++) {
    var el = guide.reviews[i]
    if(review._id == '5550c26e8c334adebc7c5dc3') {
        review = el
    }
}

如果您使用lodash,您还可以使用indexBy方法将数组转换为散列,其中所有项都由指定字段标识:

var _ = require('lodash')
var reviews = _.indexBy(guide.reviews, '_id')
// Then you can do reviews['5550c26e8c334adebc7c5dc3']