node.js - 无法使用 $project 获取特定的数据库值

标签 node.js mongodb mongoose mongodb-query aggregation-framework

我试图在使用聚合和项目后获取标题,但由于某种原因它没有显示在我的结果中。我问了另一个关于如何对文档数组进行排序的问题,似乎我必须使用聚合才能完成我认为是微不足道的练习。我错了!不管怎样......我已经评论了代码来解释我想要做什么。

Product.aggregate([
  {
    $match: {
      // get the passed in ID which is a string and needs to be converted to ObjectId format (is there a better way to do this?)
      _id: new mongoose.Types.ObjectId(productId)
    }
  },
  {
    // deconstruct the array of objects
    $unwind: "$requests"
  },
  {
    // sort in required order of display
    $sort: {
      "requests.requestDt": -1
    }
  },
  {
    // group by the product ID and push into new array
    $group: {
      "_id": productId,
      "requests": {
        $push: "$requests"
      }
    }
  },
  {
   // project the data I want to display in my view
    $project: {
      "_id": 1,
      "title": 1,
      "requests": 1,
    }
  }
])

当我控制台记录此内容时,我得到如下输出:

[{
    "_id": "5c4aaa22d0f10e038999afca",
    "requests": [{
            "_id": "5c4b2925d47f6e0a79378010",
            "userId": "5c25cddc73d10c02a75b3d55",
            "firstName": "test",
            "requestDt": "2019-01-25T15:20:05.410Z"
        },
        {
            "_id": "5c4b28e8d47f6e0a7937800f",
            "userId": "5c375260a6f58308e510711a",
            "firstName": "Joe",
            "requestDt": "2019-01-25T15:19:04.258Z"
        }
    ]
}]

那么,我从项目中的 _id 获取产品 ID 以及请求,但没有标题,我不知道为什么?

这是架构:

const productSchema = new Schema({
    title: {
        type: String,
        required: true,
    },
    category: {
        type: String,
        required: true
    },
    images: [
        {
            name: {
                type: String
            }
        }
    ],
    description: {
        type: String,
        required: true
    },
    userId: {
        type: Schema.Types.ObjectId,
        ref: 'User',
        required: true
    },
    createdAt: {
        type: Date,
        default: Date.now
    },
    requests: [
        {
             userId: { type: Schema.Types.ObjectId, required: true},
             firstName: {type: String},
             requestDt: {type: Date, default: Date.now}
        }
    ]
});

更新:

我删除了 $group,现在可以访问它。我的数据现在看起来像:

[{
        "_id": "5c4aaa22d0f10e038999afca",
        "title": "Some product",
        "requests": {
            "_id": "5c4b2925d47f6e0a79378010",
            "userId": "5c25cddc73d10c02a75b3d55",
            "firstName": "test",
            "requestDt": "2019-01-25T15:20:05.410Z"
        }
    },
    {
        "_id": "5c4aaa22d0f10e038999afca",
        "title": "Some product",
        "requests": {
            "_id": "5c4b28e8d47f6e0a7937800f",
            "userId": "5c375260a6f58308e510711a",
            "firstName": "Joe",
            "requestDt": "2019-01-25T15:19:04.258Z"
        }
    }
]

所以现在所有数据都包装在一个数组中,而不是请求。但我现在有重复的数据,即:产品标题显示两次,但我只需要一次。

要访问标题,我使用 product[0].title ,对于请求,我将它们放入 for 循环中,即: for (userRequest of Product ) 并访问数据如下:serRequest.requests.motivation

这似乎是一个疯狂的漫长的路要走,只是为了按“请求”排序,所以如果有人有更好的解决方案,请发布它。

最佳答案

您需要使用$first聚合以获取 $group 中的 title 值阶段

Product.aggregate([
  { "$match": { "_id": new mongoose.Types.ObjectId(productId) }},
  { "$unwind": "$requests" },
  { "$sort": { "requests.requestDt": -1 }},
  { "$group": {
    "_id": "$_id",
    "requests": { "$push": "$requests" },
    "title": { "$first": "$title" }
  }},
  { "$project": { "_id": 1, "title": 1, "requests": 1 }}
])

关于node.js - 无法使用 $project 获取特定的数据库值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54376647/

相关文章:

node.js - 尽管表和数据库明显存在且配置正确,但仍然执行 Sequelize 'no such table:'

json - 无法运行react js项目

css - webpack:将全局样式文件导入所有组件

node.js - Windows 物联网 - Mongodb - 覆盆子

python - 如何将 mongoose/mongodb 中的 findOneAndUpdate 扩展到 500 万次更新?

javascript - 如何通过动态键读取值,形成json

javascript - MongoDB 查询优化

java - 如何在java中从mongodb中搜索不包含空值的数组?

node.js - 在 Mocha 测试中的 for 循环中进行顺序 Mongoose 查询

当超过 100 个结果时,Node.js + mongoose find 卡住 Node