mongodb, express.js. Add new doc to array of documents selector is id

Viewed 39

I want to add a new document to an array of documents. So I pass in my param which is the _id of the document I want to add to. Then I need to just add it to the array. I thought I had it working but it was actually adding a nested array to that array. I realized this because I am also trying to sort it so newly added documents are at top. So I ended up having to go back and try and fix my add query. As of now it basically just says cannot add values. This is why I have been using mongodb client, express, await.

I have been looking at mongodb manual and trying what they have but cannot get it to work, obviously something wrong with my adding of new document. Anyone see the issue or show me an example? Thanks!

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();
    }
});

Using post man this is what my json looks like and what the array of documents looks like I am trying to add to.

 {"comments": [
                {
                    "comment": "pm - test3",
                    "author": "pm - test4"
                }
            ]
        }
1 Answers
  • do the mongodb connection outside the function, no need to connect and disconnect everytime when function call, don't create unusual variables too much.
  • for push object you need to provide main key name and assign object to it.
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 });
    }

});
Related