无法在MongoDB(Mongoose)结果中选择某些字段

pw9qyyiw  于 2022-11-03  发布在  Go
关注(0)|答案(2)|浏览(145)

我遇到了一个关于mongoose结果的奇怪问题。我可以从对象中选择一个值,但不能选择另一个。
比如我打电话给

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)
            })

我得到了一个结果,并且IM控制台注销了整个产品。结果是:

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

我可以注销storePrice字段

storePrice is:  6.99

但是,如果我尝试注销dropDate和totalLikes字段,则会得到undefined

drop date is:  undefined
totalLikes is:  undefined

你知道为什么当我试图访问这些字段时,它们会返回undefined吗?即使它们存在于对象中?

gj3fmq9x

gj3fmq9x1#

这是因为Mongoose在默认情况下会对返回的文档进行水合,因此它们不是纯JavaScript对象。
如果你想返回纯JavaScript对象,你应该在你的查询中添加.lean(),这将进一步提高性能:

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

您可以在official docs中找到更多信息。

5jdjgkvh

5jdjgkvh2#

我通过字符串化然后再次解析来解决它,真的很奇怪。

相关问题