Reputation: 43
I am trying to a process an array in a mongodb collection using the c++ mongo driver. However I always end up with the error message:
terminate called after throwing an instance of mongo::MsgAssertionException'
what(): BSONElement: bad type -64
Aborted (core dumped)
I tried to find it on google, but the only answers if found told me to repair my database. I did this but the error stay.
I am really confused by this error. The collection printed by the mongo-shell seems not to be corrupted and the shell also does not claim any error (see below). So I would assume that the vector rawDataArray
generated in my code (see also below) is holding valid data. However, when I try to print the values I get the mentioned error message.
What am I doing wrong?
Thanks a lot
Michael
PS:
I am using the mongodb C++ legacy driver and the error is generated by the following piece of code:
mongo::DBClientConnection connection;
connection.connect("localhost");
mongo::BSONObj resultObj;
try
{
std::auto_ptr<mongo::DBClientCursor> cursor =
connection.query("mydb.results",
MONGO_QUERY( "_id" << mongo::OID(resultID) ) );
while (cursor->more())
{
resultObj = cursor->next();
}
}
catch( const mongo::DBException &e )
{
// error handling
}
// extract raw_data array
std::vector<mongo::BSONElement> rawDataArray;
if( resultObj.hasField("raw_data") )
{
rawDataArray = resultObj["raw_data"].Array();
}
else
{
// error handling
}
for(auto const & data : rawDataArray)
{
std::cout << data << std::endl;
}
The collection is looking like:
db.getCollection('results').find({}).pretty()
{
"_id" : ObjectId("56cf1315f7e0583e2c4ec702"),
"experiment_id" : ObjectId("56c5b8e7e1fa370a1de9d06f"),
"module_id" : ObjectId("56c5b8e7e1fa370a1de9d06e"),
"raw_data" : [
{
"id_number" : "0accb65f4fc311",
"box" : "0accb65f4fc3",
"paper" : 1,
"seed" : 1,
"length" : 0,
"time" : ISODate("2015-09-15T20:00:00.000Z")
},
{
"id_number" : "0accb65f4fc312",
"box" : "0accb65f4fc3",
"paper" : 1,
"seed" : 2,
"length" : 0,
"time" : ISODate("2015-09-15T20:00:00.000Z")
},
{
"id_number" : "0accb65f4fc313",
"box" : "0accb65f4fc3",
"paper" : 1,
"seed" : 3,
"length" : 0,
"time" : ISODate("2015-09-15T20:00:00.000Z")
},
... skipped some data here, there are 204 nearly identical elements
{
"id_number" : "0accb65f4fc3451",
"box" : "0accb65f4fc3",
"paper" : 4,
"seed" : 51,
"length" : 0,
"time" : ISODate("2015-09-15T20:00:00.000Z")
}
],
"processed_data" : []
}
Upvotes: 1
Views: 355
Reputation: 12727
You are accessing resultObj after the cursor object has been destroyed, but resultObj is merely viewing data owned by the cursor. Call getOwned on the BSONObj to get an owning copy if you need its lifetime to extend beyond the lifetime of the cursor which returned it.
Upvotes: 1