如何使用 Mongoose 在 NodeJs 中的嵌套对象或数组中查找数据?

你好,我想找到带有购物车项目块的用户购物车项目数量

我的猫鼬收藏是这样的

"username" :'anything',"email " : 'something'
"cart":[{"slug":"m-tshirts/blue-tshirt-1","quantity":"5"}]}

我试过这个代码

 UserModel.findOne({ username : 'anything','cart.slug' :'m-tshirts/blue-tshirt-1'   
 }).exec((err,data)=>{
        console.log(data.cart);

 })

但我不知道如何访问购物车中的特定“项目”。如果我使用

data.cart[0].quantity;

但是我不知道这个卡片对象的 id。那么如何获取数量?

lijunlove 回答:如何使用 Mongoose 在 NodeJs 中的嵌套对象或数组中查找数据?

您可以通过这种方式使用 projection 来查找:

db.collection.find({
  username: "anything","cart.slug": "m-tshirts/blue-tshirt-1"
},{
  cart: {
    "$elemMatch": {
      "slug": "m-tshirts/blue-tshirt-1"
    }
  }
})

它返回数组 cart,其中包含与条件匹配的元素。

[
  {
    "_id": ObjectId("5a934e000102030405000000"),"cart": [
      {
        "quantity": "5","slug": "m-tshirts/blue-tshirt-1"
      }
    ]
  }
]

示例here

另一种选择是以这种方式使用 aggregation

db.collection.aggregate({
  "$unwind": "$cart"
},{
  $match: {
    username: "anything","cart.slug": "m-tshirts/blue-tshirt-1"
  }
},{
  "$project": {
    _id: 0,"cart": 1
  }
})

它只将对象返回到符合条件的 cart 中:

[
  {
    "cart": {
      "quantity": "5","slug": "m-tshirts/blue-tshirt-1"
    }
  }
]

示例here

本文链接:https://www.f2er.com/7233.html

大家都在问