MongoDB convert Sting id atribute to ObjectId from request POST body

Viewed 70

I'm building a JamStack app in NextJs with a MongoDB database using the mongodb driver.

The client is sending a JSON POST request to an enpoint "/api/foo".

// Client side

fetch(`/api/foo/`, {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json'
    },
    body: JSON.stringify({
        "name": data.name,
        "subject": data.subject,
        "content": data.content,
        "col_id": data.colId // <-- String
    })
})

Since I can't send the ObjectId directly from the client, but from the endpoint, I have to convert the ID string sent from the client to an ObjectId of the received body attribute.

// API Endpoint /api/foo

// fooid= 24charactersID

var ObjectId = require('mongodb').ObjectID;

switch (method) {
    case 'POST':
        const postFoo = await db
            .collection("foo")
            .insertOne(req.body); /* <-- transform the sent "col_id" attribute
                                         into {"col_id": ObjectId("24charactersID")}
                                         before inserting to the database */

        res.json(postFoo);
        break

    case 'PUT':
        const updateFoo = await db
            .collection("foo")
            .update(
                { "_id": ObjectId(fooid) },
                { $set: req.body }
            );

        res.json(updateFoo);
        break
}

Is this viable?

1 Answers
// API Endpoint /api/foo

// fooid= 24charactersID

var ObjectId = require('mongodb').ObjectID;

switch (method) {
    case 'POST':
        const postFoo = await db
            .collection("foo")
            .insertOne({
                ...req.body,
                col_id: ObjectId(req.body.col_id)
             }); /* Done, Haven't tested, but this should work now */

        res.json(postFoo);
        break

    case 'PUT':
        const updateFoo = await db
            .collection("foo")
            .update(
                { "_id": ObjectId(fooid) },
                { $set: req.body }
            );

        res.json(updateFoo);
        break
}
Related