node.js - 在nodejs中使用聚合查询未获取数据
问题描述
我尝试了下面的代码,但只检查并显示了第一个匹配,其他显示为对象,为什么我无法在控制台中看到它。我有 3 位学生学科老师,也为相同的课程制定了架构。尝试聚合
Student.aggregate([
{
$match: { name: 'abcd'}
},
{
$lookup:
{
from:'teachers',
pipeline: [{ $match: { name: 'pqrs' } },],
as: "teacherLookup"
}
},
{
$lookup:
{
from:'subjects',
pipeline: [{ $match: { name: 'computer' } }],
as: "subjectLookup"
}
}
]).then(function (res) {
console.log(res);
res.forEach(function(students){
let id = students._id;
console.log(id+ ' got id ')
}
output
student
name:'abcd' -- its fetched and other two not displaying values only shows object
teacherLookup: [ [Object] ]
subjectLookup: [ [Object] ]
解决方案
你在那里只是为了投射一些你必须使用$project
舞台的东西。
在这里,我添加了查询:
Student.aggregate([
{
$match: { name: 'abcd'}
},
{
$lookup:{
from:'teachers',
pipeline: [
{
$match: { name: 'pqrs' }
},
{
$project:{
"_id":1
}
}
],
as: "teacherLookup"
}
},
{
$lookup:
{
from:'subjects',
pipeline: [
{
$match: { name: 'computer' }
},
{
$project:{
"_id":1
}
}
],
as: "subjectLookup"
}
}
])
有关更多信息,$project
请参阅此处。
希望这会有所帮助:)
推荐阅读
- typescript - TypeScript:如何制作一个根据条件返回数组的条件类型?
- javascript - 将特定符号添加到 reg ex javascript
- python - If clause passes, even though it should be invalid
- chart.js - Datalabels of Chart JS can not display full values
- visual-studio - GitHub command 'github.copilot.generate' not found
- python - MarkerCluster does not have a tooltip feature I would like to use the Hover option to display details on clusters in python language using Folium
- xamarin.forms - Xamarin.Forms:为什么我的两侧被切断,尽管仍有空间
- azure-devops - 在 Azure Devops 中发布成功时自动更改工作项状态
- ajax - 有没有更简单的方法来允许 AJAX 加载 Wordpress 短代码?
- angular - rasa 聊天机器人无法使用 Angular 应用程序