javascript - 如何在 NodeJS 回调中获取 MongoDB 的 collection.aggregate() 的结果?
问题描述
我有以下users
收藏:
{
"_id" : ObjectId("5b29ba37cd0b1726068731c3"),
"name" : "Gym Dog",
"profilePicUrl" : "https://i.imgur.com/mPStaKV.png",
"totalProgress" : {
"goal" : 300,
"progress" : 0,
"percentage" : 0
},
"goals" : [
{
"description" : "Running",
"goal" : 100,
"progress" : 0,
"percentage" : 0
},
{
"description" : "Lifting",
"goal" : 200,
"progress" : 0,
"percentage" : 0
}
],
"days" : [
{
"weekday" : "Sunday",
"content" : ""
},
{
"weekday" : "Monday",
"content" : ""
},
{
"weekday" : "Tuesday",
"content" : ""
},
{
"weekday" : "Wednesday",
"content" : ""
},
{
"weekday" : "Thursday",
"content" : ""
},
{
"weekday" : "Friday",
"content" : ""
},
{
"weekday" : "Saturday",
"content" : ""
}
],
"activities" : [ ]
}
我想选择goals
用户的第二个元素,Gym Dog
然后在 NodeJS 回调函数中返回结果。
以下是我在Mongo shell中所做的:
db.users.aggregate(
{ $match: { name: 'Gym Dog' }},
{ $project: {
_id: 0,
ithGoal: { $arrayElemAt: [ '$goals', 1 ] }
}}
).pretty()
Mongo shell 的结果。这也是我期望我的 NodeJS 代码输出的内容
{
"ithGoal" : {
"description" : "Lifting",
"goal" : 200,
"progress" : 0,
"percentage" : 0
}
}
以下是我在NodeJs中所做的:
mongoDB.collection('users').aggregate(
// pipeline
[
{ $match: { name: 'Gym Dog' }},
{ $project: {
_id: 0,
ithGoal: { $arrayElemAt: [ '$goals', 1 ] }
}}
],
// callback
function(err, result) {
if (err) {
throw err
}
console.log(result);
});
但是,当result
登录到控制台时,它是一个AggregationCursor {}
带有一堆无关信息的对象。它与 Mongo shell 的输出没有任何相似之处(我在这里不包括输出,因为它太长了)。
我也试过mongoDB.collection('users').aggregate().toArray(function(err, result) {});
了,但是它输出了整个 JSON 对象name
,profilePicUrl
, totalProgress
, goals
, days
, activitise
(换句话说,它从我给出的条件中没有选择任何内容)。
所以,我的问题是,如何让 NodeJS 中的回调函数将与 Mongo shell 完全相同的结果存储到result
参数中?
我正在使用 MongoDB 社区 3.6.5。提前致谢!
解决方案
语法似乎正确。请检查 MongoDB 连接 URL。但我不确定,我想是一些与数据库连接相关的问题
推荐阅读
- wordpress - 在 Wordpress 更新后使用 Wpbakery 进行编辑不起作用
- sql-server - 在 SQL Server 中,为什么 SET 语句会出现在 sp_cache_miss 扩展事件中?它会导致高CPU吗?
- javascript - 2个坐标之间的随机鼠标移动?
- python - 如何在 Django Admin 中更改 OneToOne 模型字段默认消息?
- reactjs - 反应 konva 在舞台上放大时保持一层固定
- c# - 使用反射将 XML 数组反序列化为列表
- ruby-on-rails - 无法使用 kubernets 部署 yam 文件的 command/args 部分向 kubernetes 中的 puma 提供配置文件
- jenkins - 如何在没有调用方法的情况下访问 vars/*.groovy Jenkins 库中的全局变量/函数?
- postgresql - 更新查询中的 LIMIT 1 更新所有行而不是只更新一个 postgres
- css - css - RShiny 小部件:如何为 radioButtons() 和 checkboxGroupInput() 着色?