【发布时间】:2021-03-09 10:42:33
【问题描述】:
我想将一个新文档添加到一个文档数组中。所以我传入我的参数,这是我要添加到的文档的 _id。然后我只需要将它添加到数组中。我以为我让它工作了,但它实际上是在向该数组添加一个嵌套数组。我意识到这一点是因为我也在尝试对其进行排序,因此新添加的文档位于顶部。所以我最终不得不回去尝试修复我的添加查询。到目前为止,它基本上只是说不能添加值。这也是我一直在使用mongodb客户端,express,await的原因。
我一直在查看 mongodb 手册并尝试他们所拥有的但无法使其正常工作,显然我添加新文档有问题。有人看到这个问题或给我看一个例子吗?谢谢!
app.post("/addComment/:id", async (request, response) => {
let mongoClient = new MongoClient(URL, { useUnifiedTopology: true });
try {
await mongoClient.connect();
let id = new ObjectId(request.sanitize(request.params.id));
request.body.comments = { $push: {"comments.author": "myTestPOSTMAN - 1", "comments.comment":
"myTestCommPostMan - 1"}};
let selector = { "_id":id };
//let newValues = {$push: {"comments.comment": "myTestCommPostMan - 1", "comments.author":
"myTestPOSTMAN - 1"}};
let newValues = request.body.comments;
let result = await mongoClient.db(DB_NAME).collection("photos").updateOne(selector,
newValues);
if (JSON.parse(result).n <= 0) {
response.status(404);
response.send({error: "No documents found with ID"});
mongoClient.close();
return;
}
response.status(200);
response.send(result);
} catch (error) {
response.status(500);
response.send({error: error.message});
throw error;
} finally {
mongoClient.close();
}
});
使用 post man 这就是我的 json 的样子以及我试图添加的文档数组的样子。
{"comments": [
{
"comment": "pm - test3",
"author": "pm - test4"
}
]
}
【问题讨论】:
-
曾经考虑过拉下您要编辑的文档并将其保存在内存中,然后执行您想要的所有操作,完成后只需更新整个文档
-
不,我只是想写一个查询并添加新值,认为这是一个足够简单的任务,但我也是 mongodb 的新手。我主要使用sql
标签: mongodb express mongodb-query