A
A
Alexander2015-04-29 17:14:50
MongoDB
Alexander, 2015-04-29 17:14:50

What is the correct way to handle ObjectId in Mongo?

Every time I make a PUT from the client, an object comes to the server with a string in the _id field, and I'm converting it to ObjectId manually. I think this is stupid.
How to properly handle the _id field, which looks like a string on the client, and an ObjectId object on the server?
I use node.js+express.js and don't use ORM, only native js driver, official.
An object like this should appear in the database

{
    "_id" : ObjectId("5540ed124022ad9409092f71"),
    "parameters_id" : [ 
        ObjectId("554006c8a2fa57fc0dd7e47f"), 
        ObjectId("55400b2aa2fa57fc0dd7e480")
    ],
    "name" : "Название"
}

This comes from the client
{
"parameters_id" : [ 
        "554006c8a2fa57fc0dd7e47f", 
        "55400b2aa2fa57fc0dd7e480"
        ],
"name" : "Название"
}

Further, such a piece of shit code scams a string in ObjectId
....
post: function (req, res) { //или пут не важно
            var item = req.body; 
            if (item.parameters_id) {
                for (var i = 0; i < item.parameters_id.length; i++) {
                    item.parameters_id[i] = ObjectId(item.parameters_id[i]);
                }
            }
//тут дальше инсерт в базу

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question