Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/33.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js Mongodb聚合管道从数组返回多个带$lookup的字段_Node.js_Mongodb_Express_Mongoose_Aggregation Framework - Fatal编程技术网

Node.js Mongodb聚合管道从数组返回多个带$lookup的字段

Node.js Mongodb聚合管道从数组返回多个带$lookup的字段,node.js,mongodb,express,mongoose,aggregation-framework,Node.js,Mongodb,Express,Mongoose,Aggregation Framework,我试图通过createdAt从博士后文档中获取一个排序后的评论列表,其中聚合管道将用于使用displayName和profilePhoto字段填充comments in comments字段中评论的所有者 后架构: { _owner: { type: Schema.Types.ObjectId, ref: 'User', required: true }, ... comments: [ { _owner: { type: Schema.Types.ObjectI

我试图通过createdAt从博士后文档中获取一个排序后的评论列表,其中聚合管道将用于使用displayName和profilePhoto字段填充comments in comments字段中评论的所有者

后架构:

{
  _owner: { type: Schema.Types.ObjectId, ref: 'User', required: true },
  ...
  comments: [
    {
      _owner: { type: Schema.Types.ObjectId, ref: 'User' },
      createdAt: Number,
      body: { type: String, maxlength: 200 }
    }
  ]
}
用户架构:

{
  _id: '123abc'
  profilePhoto: String,
  displayName: String,
  ...
 }
我想回报的是:

[
  {
    "_id": "5bb5e99e040bf10b884b9653",
    "_owner": {
        "_id": "5bb51a97fb250722d4f5d5e1",
        "profilePhoto": "https://...",
        "displayName": "displayname"
    },
    "createdAt": 1538648478544,
    "body": "Another comment"
  },
  {
    "_id": "5bb5e96686f1973274c03880",
    "_owner": {
        "_id": "5bb51a97fb250722d4f5d5e1",
        "profilePhoto": "https://...",
        "displayName": "displayname"
    },
    "createdAt": 1538648422471,
    "body": "A new comment"
  }
]
我有一些工作代码,首先从聚合得到排序的注释,然后单独填充,但我希望能够通过使用聚合管道得到这个查询

当前的解决方案如下所示:

  const postComments = await Post.aggregate([
    { $match: { _id: mongoose.Types.ObjectId(postId) } },
    { $unwind: '$comments' },
    { $limit: 50 },
    { $skip: 50 * page },
    { $sort: { 'comments.createdAt': -1 } },
    {$replaceRoot: {newRoot: '$comments'}},
    {
      $project: {
        _owner: 1,
        createdAt: 1,
        body: 1
      }
    }
  ]);

  await Post.populate(postComments, {path: 'comments._owner', select: 'profilePhoto displayName' } )

你可以在下面试试

const postComments = await Post.aggregate([
  { "$match": { "_id": mongoose.Types.ObjectId(postId) } },
  { "$unwind": "$comments" },
  { "$lookup": {
    "from": "users",
    "localField": "comments._owner",
    "foreignField": "_id",
    "as": "comments._owner"
  }},
  { "$unwind": "$comments._owner" },
  { "$replaceRoot": { "newRoot": "$comments" }},
  { "$sort": { "createdAt": -1 } }
  { "$limit": 50 }
])