MongoDB ObjectId returning [object Object] in Ajax

1

In a query I make in MongoDB using Ajax and PHP, when I'm going to manipulate ObjectId already in javascript, it returns me as [Object Object]. How do I use it as a string?

Follow the $ code .ajax ()

$.ajax({
    url: 'funcoes/registroeventos.php',
    data: {
        "ref": ref
    },
    type: 'post',
    dataType: 'json',
    cache: false,
    beforeSend: function (xhr) {
    },
    error: function (jqXHR, textStatus, errorThrown) {
    },
    success: function (dados) {
        $.each(dados, function () {
            $.each(this, function (index, value) {
                alert(value);
            });
        });
    }
});

Follow the PHP code:

$ref = $_POST['ref'];
    try {
        $consulta = ['ref' => $ref, 'excluido' => 'n'];
        $opcoes = [];
        $query = new MongoDB\Driver\Query($consulta, $opcoes);
        $linhas = $conexao->executeQuery($bd . "maquinas", $query);

        echo json_encode(iterator_to_array($linhas));
    } catch (Exception $exc) {
        echo $exc->getTraceAsString();
    }

Example of Json :

[
     {"_id":{"$oid":"5aafac02dc32b7f93a3fda00"}, "ref":"DIP001", 
      "nome":"Dip Tork", "status":"setup", "excluido":"n",
       "idsetor":"5aafaba2dc32b7f93a3fd9ff"} 
]
    
asked by anonymous 23.03.2018 / 03:20

1 answer

0

By your comment, you notice that you had difficulties understanding, this JSON is actually a array of information, that is, you have positions for each item, eg:

let item = [{"_id":{"$oid":"5aafac02dc32b7f93a3fda00"}, 
             "ref":"DIP001", "nome":"Dip Tork", 
              "status":"setup", "excluido":"n",
               "idsetor":"5aafaba2dc32b7f93a3fd9ff"} ] ;

console.log(item[0]['_id']['$oid']);
console.log(item[0]['ref']);
console.log(item[0]['nome']);
console.log(item[0]['status']);
console.log(item[0]['excluido']);
console.log(item[0]['idsetor']);

In this example example, you only have one item in array which is 0 , but if you have more you have to check the quantity of items in array to fetch your items, eg

let item = [{
  "_id": {
    "$oid": "5aafac02dc32b7f93a3fda00"
  },
  "ref": "DIP001",
  "nome": "Dip Tork",
  "status": "setup",
  "excluido": "n",
  "idsetor": "5aafaba2dc32b7f93a3fd9ff"
}, {
  "_id": {
    "$oid": "5aafac02dc32b7f93a3fdaaa"
  },
  "ref": "DIP001",
  "nome": "Dip Tork",
  "status": "setup",
  "excluido": "n",
  "idsetor": "5aafaba2dc32b7f93a3fd9ff"
}];
console.log('Quantidade de itens:' + item.length);
for (i = 0; i < item.length; i++) {
  console.log('-----------------------------');
  console.log(item[i]['_id']['$oid']);
  console.log(item[i]['ref']);
  console.log(item[i]['nome']);
  console.log(item[i]['status']);
  console.log(item[i]['excluido']);
  console.log(item[i]['idsetor']);  
}
    
23.03.2018 / 12:43