Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/377.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
Javascript 有没有办法在mongoDB中找到嵌套数组中的文档_Javascript_Arrays_Node.js_Mongodb_Mongoose - Fatal编程技术网

Javascript 有没有办法在mongoDB中找到嵌套数组中的文档

Javascript 有没有办法在mongoDB中找到嵌套数组中的文档,javascript,arrays,node.js,mongodb,mongoose,Javascript,Arrays,Node.js,Mongodb,Mongoose,const userSchema=新模式{ 用户名:{ 类型:字符串, 必填项:true }, 电邮:{ 类型:字符串, 必填项:true }, 密码:{ 类型:字符串, 必填项:true }, 职位:[{ 类型:Schema.Types.ObjectId, 参考:“邮政” }], 朋友们:[{ 类型:Schema.Types.ObjectId, 参考:“用户” }], }; //正在导出架构,以便可以通过请求来访问它。 module.exports=mongoose.model'User',u

const userSchema=新模式{ 用户名:{ 类型:字符串, 必填项:true }, 电邮:{ 类型:字符串, 必填项:true }, 密码:{ 类型:字符串, 必填项:true }, 职位:[{ 类型:Schema.Types.ObjectId, 参考:“邮政” }], 朋友们:[{ 类型:Schema.Types.ObjectId, 参考:“用户” }], }; //正在导出架构,以便可以通过请求来访问它。
module.exports=mongoose.model'User',userSchema 如果在post模型中有一个指向用户模型的链接,即标识作者的某个字段,则可以使用for循环来搜索用户朋友的帖子

我不知道这是否是最好的解决方案,但我希望它能有所帮助

作为提示,您应该使用异步语法而不是承诺,这有助于纠正错误

异步函数getFriendsPostsreq,res{ /*在这个数组中,我们将存储 用户朋友的帖子*/ 让posts=[]; 试一试{ //我们检查用户是否存在 让user=user.findByIdreq.params.id; //如果它不存在,我们将发送一条消息 如果未找到!user res.status404.sendUser; 否则{ /*这里我们比较朋友的id和 post模型中的friends with creator字段*/ 对于user.friends的朋友{ 对于Post.find的创建者{ /*如果有一个匹配我们发送 将其发送到post数组*/ iffriend.\u id.equalscreator.\u id{ posts.pushcreator; } } } /*最后,我们发送带有帖子的数组*/ 关于发送邮件的决议; } }捕手{ res.status500.send内部服务器错误; }
} 如果我假设Post模式是这样的话

{
    title: String,
    content: String,
    owner: { type: Schema.Types.ObjectId, ref: 'User'}
}
User.aggregate([
  {
    $match: {
      _id: mongoose.Types.ObjectId(req.params.id)
    }
  },
  {
    $lookup: {
      from: "posts", // this should be the posts collection name, It may be 'Post' not 'posts', check it
      let: {
        friendsIDs: "$friends"
      },
      pipeline: [
        {
          $match: {
            $expr: {
              $in: ["$owner", "$$friendsIDs"]
            }
          }
        }
      ],
      as: "friendsPosts"
    }
  }
]).then(result => {
    // the aggregate pipeline is returning an array
    // but we are sure it will be an array of only one element as we are searching for only one user, so we can use result[0]

    result = result || []; // double check the result array
    result[0] = result[0] || {}; // double check the user object
    var posts = result[0].friendsPosts; // here is the friends posts array

    // return the posts array
    res.json(posts);
})
然后我们可以使用聚合管道来获取一些用户的好友帖子

诸如此类

db.users.aggregate([
  {
    $match: {
      _id: "userId1" // this should be of type ObjectId, you need to convert req.params.id to ObjectId (something like: mongoose.Types.ObjectId(req.params.id) instead of 'userId1')
    }
  },
  {
    $lookup: {
      from: "posts",
      let: {
        friendsIDs: "$friends"
      },
      pipeline: [
        {
          $match: {
            $expr: {
              $in: ["$owner", "$$friendsIDs"]
            }
          }
        }
      ],
      as: "friendsPosts"
    }
  }
])
你可以在这里测试

请随意替换这些“userId1”、“userId2”、“postId1”、“postId2”和。。在这个链接中与您的真实用户和帖子ID

通过这种方式,您可以通过一个查询而不是两个查询获得某个用户的好友帖子

那么函数就是这样的

{
    title: String,
    content: String,
    owner: { type: Schema.Types.ObjectId, ref: 'User'}
}
User.aggregate([
  {
    $match: {
      _id: mongoose.Types.ObjectId(req.params.id)
    }
  },
  {
    $lookup: {
      from: "posts", // this should be the posts collection name, It may be 'Post' not 'posts', check it
      let: {
        friendsIDs: "$friends"
      },
      pipeline: [
        {
          $match: {
            $expr: {
              $in: ["$owner", "$$friendsIDs"]
            }
          }
        }
      ],
      as: "friendsPosts"
    }
  }
]).then(result => {
    // the aggregate pipeline is returning an array
    // but we are sure it will be an array of only one element as we are searching for only one user, so we can use result[0]

    result = result || []; // double check the result array
    result[0] = result[0] || {}; // double check the user object
    var posts = result[0].friendsPosts; // here is the friends posts array

    // return the posts array
    res.json(posts);
})
希望能有帮助

使现代化 如果我们需要对火种进行分类,然后限制它们

我们可以使用以下方法

db.users.aggregate([
  {
    $match: {
      _id: "userId1"
    }
  },
  {
    $lookup: {
      from: "posts",
      let: {
        friendsIDs: "$friends"
      },
      pipeline: [
        {
          $match: {
            $expr: {
              $in: [
                "$owner",
                "$$friendsIDs"
              ]
            }
          }
        }
      ],
      as: "friendsPosts"
    }
  },
  {
    $unwind: "$friendsPosts" // unwind the array to get a stream of documents
  },
  {
    $sort: {
      "friendsPosts.createdAt": 1 // then sort the posts by the createdAt Date in ascending order
    }
  },
  {
    $group: { // then group the posts again after sorting
      _id: "$_id",
      friendsPosts: {
        $push: "$friendsPosts"
      }
    }
  },
  {
    $project: { 
      friendsPosts: {
        $slice: ["$friendsPosts", 2] // this is to limit the posts
      }
    }
  }
])

你可以在这里测试它

你能在问题中添加帖子模式吗?有没有一种方法可以对好友进行限制和排序呢?有,我已经更新了我的答案,你能再检查一遍看最后的更新吗?太好了!还有一件事,这是否可以说我只想获得在特定日期之后创建的帖子?我们可以在$sort之后和$group之前使用另一个$match阶段,来获得在某个日期之后创建的帖子,试试这个