![](/img/trans.png)
[英]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.