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

Time:10-24

Below is my code to find the review from the reviews array in a restaurant object and display the review if the _id matches:

Restaurant Object:

{
  _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)

The output I get is:

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

More of this as I am missing some functionality somewhere.

How can I get the output which is the returned review based on the review id as input?

CodePudding user response:

"It says r.toArray is not a function" - You show us that you got a find cursor, Indeed FindCursor has a method called 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:

  • next()
  • toArray()
  • forEach()

There is many way you can iterate of cursor,

Using async iterator:

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

toArray

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

And much more! they support callbacks, node stream api etc... But this two method is modern.

  • Related