[英]Trying to find index of ObjectId in Mongo DB with indexOf
[英]Simple $lookup “left join” of the ObjectId of two collections not working in Mongo DB
我正在使用帶有 node.js 和雙簧管的 Mongo DB Atlas(雙簧管將結果流式傳輸到 html)。 我對這一切都很陌生,只是學習了所有這些技術,所以用更簡單的術語解釋會很受歡迎。
目標是在兩個 collections 之間進行 $lookup,在本例中,將“review”集合到“place”。 我研究了類似的答案,但要么不起作用,要么使用的是字符串,而不是 ObjectIds。
這很簡單,只需連接兩個 collections 的 ObjectId,但是在使用雙簧管時,我無法從“位置”的“左連接”集合中提取數據(參見底部的雙簧管代碼,FWIW)。
下面是從collections看一個文檔,然后是代碼。 我究竟做錯了什么? 我嘗試將它們轉換為字符串並加入.toString() 和.str,並為localField 和foreignField 加上'place_id.ObjectId' 和'_id.ObjectId'。 另一件事是,我如何查看 cursor 中的內容以知道我得到了什么? debug(cursor.ToArray()) 不起作用。 提前致謝。
review
({
"_id": { "$oid": "5fd27fd9647f7bb815c4c946" },
"place_id": { "$oid": "5fbc37c4fc13ae680b00002b" }, // connect this...
"user_id": { "$oid": "5fbc10ecfc13ae232d000068" },
"title": "Black Forest -- unforgettable!",
"description": "The forest was great.",
"score": { "$numberInt": "5" }
}
place
{
"_id": { "$oid": "5fbc37c4fc13ae680b00002b" }, // connected to _id above
"name": "Black Forest (Schwarzwald)",
"category": "activity",
"city": "Freiburg",
"country": "Germany",
"description": "The Black Forest (German: Schwarzwald [ˈʃvaʁtsvalt] (About this soundlisten)) is a large forested mountain range.]",
"image": { "filename": "1607629020164_black_forest.jpg", "mime": "image/jpeg" },
"state": ""
})
router.get('/', async (req, res, next) => {
debug('get all reviews api');
try {
const q = req.query.q;
const collation = { locale: 'en_US', strength: 1 };
const matchStage = {};
if (q) {
matchStage.$text = { $search: q };
}
const pipeline = [
{
$match: matchStage,
},
{
$lookup: {
from: 'place',
localField: 'place_id',
foreignField: '_id',
as: 'place',
},
},
];
const connection = await db.connect();
const cursor = connection.collection('review').aggregate(pipeline, { collation: collation });
// write the JSON file
res.type('application/json');
res.write('[\n');
for await (const doc of cursor) {
res.write(JSON.stringify(doc));
res.write(',\n');
}
res.end('null]');
} catch (err) {
sendError(err, res);
}
});
cursor 成為雙簧管並成為“物品”。 在將其放入 html 時,我希望使用諸如{item.place.name}
之類的模板字符串來獲取數據。 這就是我訪問它的方式,對吧?
const performSearch = () => {
seen = 0;
$('stream-data-spinner').removeClass('d-none');
$('#search-results').html('');
const formData = $('#search-place-form').serialize();
oboe('/api/review?' + formData)
.node('![*]', (item) => {
if (item) {
chunk.push(item);
if (chunk.length >= 1000) {
showChunk(chunk);
}
}
return oboe.drop;
})
.done((_) => {
// show the last chunk
showChunk(chunk);
// hide the spinner
outputSpinner.classList.add('d-none');
})
.fail((res) => {
// show the error
outputSeen.textContent = `ERROR: network error`;
outputSeen.classList.add('text-danger');
outputSpinner.classList.add('text-danger');
});
};
從您的 MongoDB 聚合查詢中,您的place
字段是一個數組。 您可能想要$unwind將其展平為 object 以便您的雙簧管代碼訪問它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.