首页 > 解决方案 > 将 mongoDB 游标转换为 JSON

问题描述

我有一个使用快速服务器设置的 mongoDB 数据库。

我尝试访问文档中数组内的对象。

我有这条路线:

app.get("/api/" + BLOGS_COLLECTION + "/:blogId" + "/post" + "/:postId", function (req, res) {
db.collection(BLOGS_COLLECTION).aggregate([
    { $match: { _id: req.params.postId } }, {
        $project: {
            posts: {
                $filter: {
                    input: "$posts",
                    as: "posts",
                    cond: { $eq: ["$$posts._id", req.params.postId] }
                }
            }
        }
    }].toArray((err, doc) => {
        console.log(doc)
        if (err) {
            handleError(res, err.message, "Failed to get post");
        } else {
            res.status(200).send(doc);
        }
    }));
});

但它返回一个错误:

[{(intermediate value)},{(intermediate value)}].toArray is not a function

如果我不使用 toArray 而是使用普通函数,则无法构造为 json 将其发送到前面。

我不使用猫鼬。

如果上面的代码不起作用,我怎样才能只查询数组中我想要的对象?

PS:这就是我的数据库的制作方式:

_id:60336bcc961785586471938b
title:"<p>ttttttttttttttttttttttttttt</p>"
description:"<p>tttttttttttttttttttttttttt</p>"
authorId:"60336bb5961785586471938a"
createDate:2021-02-22T08:31:08.889+00:00
posts:
  0:
   _id:"53394732-d60b-c869-1fed-1fb82c03780f"
   title:"<p>iiiiiiiiiiiiiiiiiiiiiiiiiiiii</p>"
   content:"<p>iiiiiiiiiiiiiiiiiiii</p>"
   date:"2021-02-22T08:31:14.911Z"

标签: node.jsmongodbexpress

解决方案


您需要调用toArray从聚合返回的游标引用,而不是聚合数组:

db.collection(BLOGS_COLLECTION).aggregate([
  { $match: { _id: req.params.postId } },
  {
    $project: {
      posts: {
        $filter: {
          input: "$posts",
          as: "posts",
          cond: { $eq: ["$$posts._id", req.params.postId] }
        }
      }
    }
  }
],
(err, cursor) => {
  if (err) {
    handleError(res, err.message, "Failed to get post");
  } else {
    cursor.toArray((error, documents) => {
      if (error) { return handleError(res, error.message, "Failed to get post"); }
      console.log(documents)
      res.status(200).send(documents);
    });
  }
});

MongoDB 聚合管道


推荐阅读