下面是我的代碼,用于從餐廳物件的評論陣列中查找評論,并在 _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
},
索引.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作為輸入獲得回傳評論的輸出?
uj5u.com熱心網友回復:
“它說r.toArray不是一個函式” ——你告訴我們你有一個查找游標,確實FindCursor有一個名為toArray.
方法/cursor.toArray/
find() 方法回傳管理查詢結果的 FindCursor。您可以使用以下游標方法之一遍歷匹配的檔案:
- 下一個()
- toArray()
- forEach()
有很多方法可以迭代游標,
使用異步迭代器:
for await (let doc of collection.find({})) {
console.log(doc);
}
陣列
let docs = await collection.find({}).toArray();
以及更多!它們支持回呼、節點流 api 等......但這兩種方法是現代的。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/335963.html
