node.js - 将 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"
解决方案
您需要调用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);
});
}
});
推荐阅读
- c++ - 在 Visual Studio (C++) 中找不到配置属性
- python - 当我运行这个 python 代码时 PHP 不打印输出
- .net - VS Code(.NET Core SDK 无法定位.NET Core)错误
- javascript - 如何处理无限循环错误javascript
- jquery - 如何在可拖动行中设置正确的列宽?
- uno-platform - Uno 平台弹出菜单子项放置在 Andorid 上的可见区域之外
- azure - 需要 az acr 构建命令信息
- python - 如何从函数内部附加全局列表
- html - safari 上的 navigator.credentials
- python - ElementTree、.set() 和迭代