Home > database >  Unable to select certain fields in MongoDB (Mongoose) result
Unable to select certain fields in MongoDB (Mongoose) result

Time:10-18

I've ran into a bit of an odd issue with a mongoose result. I can select one value from the object, but not another.

For example I'm calling

Product.find({"name": {$regex: search), '$options': 'i'}})
            .select('dropDate storePrice totalLikes')
            .limit(1)
            .exec((err, product) => {
                if (err) console.log('[ERROR] Unable to get product. ', err)
                console.log('Product found is: ', product)
                console.log('storePrice is: ', product[0].storePrice)
                console.log('dropDate is: ', product[0].dropDate)
                console.log('totalLikes is: ', product[0].totalLikes)
                resolve(product)
            })

I get a result and im console logging out the entire product. The result is:

Product found is:  [
  {
    _id: new ObjectId("614f5c8f4b004b4d4dc82e4f"),
    storePrice: 6.99,
    dropDate: 2021-08-21T15:00:00.000Z,
    totalLikes: 2158
  }
]

I can log out the storePrice field

storePrice is:  6.99

However if I try to log out the dropDate and totalLikes fields I get undefined

drop date is:  undefined
totalLikes is:  undefined

Any ideas why these fields are returning undefined when i try to access them? Even though they exist in the object?

CodePudding user response:

I solved it by stringifying and then parsing it again, really odd.

CodePudding user response:

It's because Mongoose by default hydrate the documents returned, so they are not pure JavaScript objects.

If you want to return pure JavaScript objects, you should add .lean() to your query. That will in addition increase the performance:

Product.find({"name": {$regex: search), '$options': 'i'}})
            .select('dropDate storePrice totalLikes')
            .limit(1)
            .lean()

You can find more info in the official docs.

  • Related