Mongodb 按Id获取文档时,使用$addFields动态填充字段

Mongodb 按Id获取文档时,使用$addFields动态填充字段,mongodb,mongoose,aggregation-framework,Mongodb,Mongoose,Aggregation Framework,在MongoDB集合中运行getById()函数时,我想使用$aggregate和$addFields动态填充字段。基本上,我想做的是从一个名为“history”的属性中提取对象数组中的最后一个元素,并将其动态填充到一个名为“activeStatus”的字段中,该字段是一个对象。这段特殊的代码如下所示: await db.collection("staffmembers").aggregate([{ $addFields: { activeStatus: { $arrayElemAt: ["$h

在MongoDB集合中运行getById()函数时,我想使用
$aggregate
$addFields
动态填充字段。基本上,我想做的是从一个名为“history”的属性中提取对象数组中的最后一个元素,并将其动态填充到一个名为“activeStatus”的字段中,该字段是一个对象。这段特殊的代码如下所示:

await db.collection("staffmembers").aggregate([{ $addFields: { activeStatus: { $arrayElemAt: ["$history", -1.0] } } }, { $out: "staffmembers" }]);
{
    "_id": <id value>,
    "type": "permanent",
    "gender": "female",
    "history": [
        {
            "endDate": "2018-10-31T12:27:17.721Z",
            "stage": "training",
            "completed": true,
            "startDate": "2018-10-30T13:41:18.714Z"
        },
        {
            "stage": "active",
            "completed": false,
            "startDate": "2018-10-31T12:27:17.572Z"
        }
    ]
}
完整的getById()函数如下所示:

exports.getById = async function(req, res) {
  let doc;
  let MongoClient = await require("../config/database")();
  let db = MongoClient.connection.db;

  let request = new EndpointRequestController(
    req,
    res,
    // Allowed Parameters
    {
      id: {
        type: String
      }
    },
    [
      // Required Parameters
      "id"
    ]
  );

  await db.collection("staffmembers").aggregate([{ $addFields: { activeStatus: { $arrayElemAt: ["$history", -1.0] } } }, { $out: "staffmembers" }]);

  try {
    doc = await StaffMember.findOne(
      {
        _id: request.parameters.id
      },
      {}
    ).exec();
    if (doc) req.documentCount = 1;
  } catch (err) {
    return request.sendError("An error occurred while trying to find existing records.", err);
  }

  res.send(doc);
};
虽然我没有收到任何错误,但在生成的文档中看不到“activeStatus”

在这种情况下我能做些什么吗?如果是这样,我错过了什么

顺便说一下,我的文档如下所示:

await db.collection("staffmembers").aggregate([{ $addFields: { activeStatus: { $arrayElemAt: ["$history", -1.0] } } }, { $out: "staffmembers" }]);
{
    "_id": <id value>,
    "type": "permanent",
    "gender": "female",
    "history": [
        {
            "endDate": "2018-10-31T12:27:17.721Z",
            "stage": "training",
            "completed": true,
            "startDate": "2018-10-30T13:41:18.714Z"
        },
        {
            "stage": "active",
            "completed": false,
            "startDate": "2018-10-31T12:27:17.572Z"
        }
    ]
}
{
“_id”:,
“类型”:“永久”,
“性别”:“女性”,
“历史”:[
{
“结束日期”:“2018-10-31T12:27:17.721Z”,
“阶段”:“培训”,
“完成”:正确,
“起始日期”:“2018-10-30T13:41:18.714Z”
},
{
“阶段”:“活动”,
“已完成”:错误,
“开始日期”:“2018-10-31T12:27:17.572Z”
}
]
}
这是我想制作的文件:

{
    "_id": <id value>,
    "type": "permanent",
    "gender": "female",
    "history": [
        {
            "endDate": "2018-10-31T12:27:17.721Z",
            "stage": "training",
            "completed": true,
            "startDate": "2018-10-30T13:41:18.714Z"
        },
        {
            "stage": "employed",
            "completed": false,
            "startDate": "2018-10-31T12:27:17.572Z"
        }
    ],
    "activeStatus": {
            "stage": "employed",
            "completed": false,
            "startDate": "2018-10-31T12:27:17.572Z"
    }
}
{
“_id”:,
“类型”:“永久”,
“性别”:“女性”,
“历史”:[
{
“结束日期”:“2018-10-31T12:27:17.721Z”,
“阶段”:“培训”,
“完成”:正确,
“起始日期”:“2018-10-30T13:41:18.714Z”
},
{
“阶段”:“雇佣”,
“已完成”:错误,
“开始日期”:“2018-10-31T12:27:17.572Z”
}
],
“活动状态”:{
“阶段”:“雇佣”,
“已完成”:错误,
“开始日期”:“2018-10-31T12:27:17.572Z”
}
}
此行:

wait db.collection(“staffmembers”).aggregate([{$addFields:{activeStatus:{$arrayElemAt:[“$history”,-1.0]}}},{$out:“staffmembers”}])

返回类型,因为您正在使用raw node.js MongoDB驱动程序。所以实际上没有执行数据库调用

有两种方法可以解决此问题:

1) 使用mongoose API:

await StaffMember.aggregate([{ $addFields: { activeStatus: { $arrayElemAt: ["$history", -1.0] } } }, { $out: "staffmembers" }]);
2) “强制”光标执行查询(使用
next()
toArray()


我猜aggregate前面缺少await,你能试试吗?我在aggregate块前面添加了“await”,但仍然不行。