【问题标题】:mongodb, express.js. Add new doc to array of documents selector is idmongodb,express.js。将新文档添加到文档选择器数组是 id
【发布时间】: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


【解决方案1】:
  • 在函数外做mongodb连接,函数调用时不需要每次都连接和断开,不要过多创建异常变量。
  • 对于推送对象,您需要提供主键名称并为其分配对象。
let mongoClient = new MongoClient(URL, { useUnifiedTopology: true });
await mongoClient.connect();
app.post("/addComment/:id", async (request, response) => {

    try {

        let result = await mongoClient.db(DB_NAME).collection("photos").updateOne(
            { "_id": new ObjectId(request.sanitize(request.params.id)) }, 
            { $push: { comments: request.body.comments } }
        );
        if (JSON.parse(result).n <= 0) {
            response.status(404).send({ error: "No documents found with ID" });
            return;
        }
        response.status(200).send(result);

    } catch (error) {
        response.status(500).send({ error: error.message });
    }

});

【讨论】:

  • 啊,我明白了。好吧,我能够从您提供的内容中学习并成功添加一个对象。你为什么要索引 0?
  • 我以为你在传递一个数组,我刚刚更正了。
  • 基本上添加这样的东西 let string = {author: "myname", comment: "mycomment"};但是像你一样索引它我可以将新添加的文档放置到所需的索引中吗? Nm 试过了,什么都没做
  • 你在说什么索引comments数组元素索引?没有 $push 将在数组末尾添加对象。表示最后一个元素。
  • 是的,我认为通过更改索引会将其推送到该索引,但它没有做任何事情
猜你喜欢
  • 2014-07-29
  • 2021-06-17
  • 2015-12-21
  • 2012-09-28
  • 2019-04-28
  • 2017-09-16
  • 2012-04-12
  • 1970-01-01
  • 2019-11-12
相关资源
最近更新 更多