Mark
Mark

Reputation: 5088

Mongoose id function returning null

I'm trying to get a sub-document from MongoDB. I can get the parent document, which looks like:

    {
        "_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."
            }
        ]
    }

When I do:

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

I see:

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' }]

Which is fine. But then when I try to get the review using the Mongoose id function, I always get back null:

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

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

With result:

review is
null

Any idea what I'm doing wrong?

Upvotes: 2

Views: 1964

Answers (2)

Kevin B
Kevin B

Reputation: 95022

The MongooseDocumentArray.id(id) method searches the document array for an _id property, but your subdocuments don't have an _id property, they instead have id. You'll either have to change it to _id, or use a plain old .filter() or similar workaround.

Upvotes: 2

ItalyPaleAle
ItalyPaleAle

Reputation: 7306

I may be wrong, but I've never seen that sort of API in Mongoose before.

document.id exists, but it's a function that returns the stringified version of the _id field.

In your case, you can just go through the list with a loop and select the one you want.

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

If you use lodash, you can also use the indexBy method to convert the array to an hash in which all items are identified by the specified field:

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

Upvotes: 0

Related Questions