Currently in the process of reconstructing an arrayObject by iterating through elements obtained from an ajax .get request of MongoDB documents.
The arrayObject is close to being correct, but it lacks proper comma separation between the documents within the array.
This appears to be causing the issue where
console.log(arrayObject[0].name);
returns undefined
.
When attempting to use an if/else statement to avoid having a leading comma, the if
condition is skipped.
function reBuild(returnValue)
{
var docs = returnValue;
var returnedVal = [];
for (var i=0; i<docs.length; i++){
if (returnedVal.length === 0)
{
returnedVal.push('{' + 'title: "' + docs[i].title + '", quantity: ' + docs[i].quantity + ', _id: "' + docs[i]._id + '"}');
}
else
{
returnedVal.push(', {' + 'title: "' + docs[i].title + '", quantity: ' + docs[i].quantity + ', _id: "' + docs[i]._id + '"}');
}
console.log(returnedVal[i]);
}
console.log(returnedVal[0].title);
}
console.log(returnedVal[i]);
[15:20:02.946] "{title: "Sample1", value: 2, _id: "530c12c66e6b0de318000001"}"
[15:20:02.946] ", {title: "Sample2", value: 4, _id: "530c12cc6e6b0de318000002"}"
Retrieving MongoDB data via .get:
function getAll(res) {
db.collection('demo').find().sort( { value: 1 } ).toArray(function (err, docs) {
console.log("Received Documents: " + utils.inspect(docs));
// Each document has the structure: { _id: ObjectID, title: 'string', quantity: int}
res.json({docs: docs});
});
}
The output of the documents in the terminal console looks like this:
[ { _id: 530c12c66e6b0de318000001,
title: 'Sample1',
quantity: 2 },
{ title: 'Sample2',
quantity: 4,
_id: 530c12cc6e6b0de318000002 } ]
I am aiming to retrieve an arrayObject
containing MongoDB documents, create a new variable from the arrayObject using object.foo
, and then reconstruct an arrayObject
with all the foobar values once they are ranked.
There is another function responsible for performing calculations on variables for ranking purposes.