mongodb, express.js. 문서 배열에 새 문서 추가 선택기는 id입니다.

Nov 26 2020

문서 배열에 새 문서를 추가하고 싶습니다. 따라서 추가하려는 문서의 _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();
    }
});

포스트 맨을 사용하면 내 json이 어떻게 생겼고 문서 배열이 추가하려는 것처럼 보입니다.

 {"comments": [
                {
                    "comment": "pm - test3",
                    "author": "pm - test4"
                }
            ]
        }

답변

turivishal Nov 26 2020 at 21:42
  • 함수 외부에서 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 });
    }

});