【问题标题】:How to find document's array item by its "_id" field in MongoDB (Mongoose)?如何通过 MongoDB (Mongoose) 中的“_id”字段查找文档的数组项?
【发布时间】:2022-01-08 19:53:32
【问题描述】:

我有以下架构(NestJS + Mongoose):

@Schema({ timestamps: true })
export class Listing {
  @Prop({
        type: [{
            bidderId: { type: Types.ObjectId, required: true, select: false, ref: User.name, index: true },
            amount: { type: Number, required: true },
            date: { type: Date, required: true }
        }],
        select: false
    })
        bids!: Bid[]
}

所以基本上每个listing 文档都有一个bids 数组。
现在我注意到 mongoDB(或 mongoose)会自动为我放入 bids 数组的每个投标项目创建 _id 字段。

我的问题是,如果我有一个出价的_id,我如何从列表的出价数组中查询它的项目?类似:

  // Adding a new bid to the listing, and retrieving the updated listing
  const listingWithAddedBid = await this.listingModel.findByIdAndUpdate(listingId, {
    $push: {
        bids: {
            $each: [{
                amount: bidInfo.amount,
                bidderId: new Types.ObjectId(user.id),
                date: new Date()
            }],
            $sort: { amount: -1 }
        }
    }
}, { new: true })

  // Getting the new bid's _id from the array (it will be at index 0 because we sort buy amount)
  const newBidId = listingWithAddedBid.bids[0]._id

  // here how can I query the entire bid item from the array with 'newBidId'? this won't work
  this.listingModel.findById(newBidId) // returns null

【问题讨论】:

    标签: javascript node.js mongodb mongoose


    【解决方案1】:

    https://docs.mongodb.com/manual/tutorial/query-array-of-documents/ https://docs.mongodb.com/manual/indexes/#default-_id-index

    this.listingModel.findOne({ "bids._id": newBidId, {}, {}, (error, doc) =>
            {
             if (error) {
                    ....
                  }
                  if (doc) {
                    ....
                  } else {
                    ...//'Not Found';
                  }
            });
    

    【讨论】:

    • 顺便问一下,这个有索引吗?或者这将遍历所有列表,直到找到匹配项?因为我不知道嵌套对象的_id 被索引了
    • 已编辑,有一些参考
    猜你喜欢
    • 2015-09-19
    • 2015-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-14
    • 2020-09-18
    • 1970-01-01
    • 2013-02-06
    相关资源
    最近更新 更多