【问题标题】:How to select only products with ids from ids array. MongoDB如何从 ids 数组中仅选择具有 ids 的产品。 MongoDB
【发布时间】:2021-10-07 08:21:51
【问题描述】:

我正在获取所有产品并使用 mongoDB 填充类别。 此外,我有包含类别 ID 的数组,我只想获取在类别对象中具有该 ID 的产品。 如何只选择这个产品?

arr of ids [ '615e94cab42d2274f0481232' ]

arr of products [
  {
    _id: new ObjectId("615e945cb42d2274f0481211"),
    image: '',
    category: { _id: new ObjectId("615da90b689b8ef91fa90afd"), name: 'Разное' },
    name: '435пукп',
    type: 'В упаковке',
    piecesPerPackage: 2,
    pricePerPiece: 1,
    pricePerPackage: 2,
    weight: 12,
    description: 'вапвап'
  },
  {
    _id: new ObjectId("615eaa08f68e788c63817641"),
    image: '',
    category: { _id: new ObjectId("615e94cab42d2274f0481232"), name: '2' },
    name: '2',
    type: 'В упаковке',
    piecesPerPackage: 2,
    pricePerPiece: 2,
    pricePerPackage: 2,
    weight: 2,
    description: '2'
  }
]

async sortCatalog(arr) {
        const products = await CatalogModel.find().lean()
            .populate("category", "name").select('-__v');
        console.log("arr of ids", arr)
        console.log("arr of products", products)
    }

【问题讨论】:

  • 之后你可以使用 $lookup 和 $match

标签: javascript mongodb express mongoose select


【解决方案1】:

使用category._id 找到它。

await CatalogModel.find({'category._id':new ObjectId("615e94cab42d2274f0481232")})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-03
    • 1970-01-01
    相关资源
    最近更新 更多