如何根据 mongoDB 中的搜索 ID 显示数组值?

How do I a display an array value based on a search id in mongoDB?

下面是我的代码,用于从餐厅对象的评论数组中查找评论,并在 _id 匹配时显示评论:

餐厅对象:

{
  _id: new ObjectId("61723c7378b6d3a5a02d908e"),
  name: 'The Blue Hotel',
  location: 'Noon city, New York',
  phoneNumber: '122-536-7890',
  website: 'http://www.bluehotel.com',
  priceRange: '$$$',
  cuisines: [ 'Mexican', 'Italian' ],
  overallRating: 0,
  serviceOptions: { dineIn: true, takeOut: true, delivery: true },
  reviews: [
    {
      _id: new ObjectId("61736a0f65b9931b9e428790"),
      title: 'dom',
      reviewer: 'firuu',
      rating: 4,
      dateOfReview: '25/1/2002',
      review: ' bruh'
    }
  ]
}

 async get(reviewId) {

    const restaurantsCollection = await restaurants();
    reviewId = ObjectId(reviewId)
    const r = await restaurantsCollection.find({reviews: {$elemMatch: {_id: reviewId}}})
    return r
    
  },

index.js:

a = await reviews.get("61736a0f65b9931b9e428790")
console.log(a)

我得到的输出是:

FindCursor {
  _events: [Object: null prototype] {},
  _eventsCount: 0,
  _maxListeners: undefined,
  [Symbol(kCapture)]: false,
  [Symbol(topology)]: Topology {

更多,因为我在某处缺少一些功能。

如何根据输入的评论 ID 获取返回的评论输出?

“它说 r.toArray 不是一个函数” - 你告诉我们你有一个查找游标,确实 FindCursor 有一个方法叫做 toArray.

method/cursor.toArray/

The find() method returns a FindCursor that manages the results of your query. You can iterate through the matching documents using one of the following cursor methods:

  • 下一步()
  • toArray()
  • forEach()

有很多方法可以迭代游标,

使用异步迭代器:

for await (let doc of collection.find({})) {
   console.log(doc);
}

toArray

 let docs = await collection.find({}).toArray();

还有更多!它们支持回调、节点流 api 等...但这两种方法是现代的。