I have a JSON string that looks like this:
{
"resultType" : "history",
"currentTime" : "2011-10-22T15:46:00+00:00",
"columns" : ["date","orders","quantity","low","high","average"],
"rowsets" : [
{
"generatedAt" : "2011-10-22T15:42:00+00:00",
"rows" : [
["2011-12-03T00:00:00+00:00",40,40,1999,499999.99,35223.50],
["2011-12-02T00:00:00+00:00",83,252,9999,11550,11550]
]
}
]
}
Every time I try to parse it, I use code like this:
var data = JSON.parse(json);
console.log(data);
And the following is what is printed to the console:
{
"resultType" : "history",
"currentTime" : "2011-10-22T15:46:00+00:00",
"columns" : ["date","orders","quantity","low","high","average"],
"rowsets" : [
{
"generatedAt" : "2011-10-22T15:42:00+00:00",
"rows" : [Object]
}
]
}
I've tried a couple of things, but how can I get the data in the rows field? After parsing, the console just shows [Object].
The output you're seeing is just the way it's being displayed. If you access data.rowsets[0].rows, you can see that the JSON was indeed successfully parsed. You can also use util.inspect() when specifying the depth property to tell Node.js to recurse deeper when formatting the object.
Here is an example using util.inspect():
var data = JSON.parse(json);
// a null depth means to recurse indefinitely
console.log(util.inspect(data, { depth: null }));
Have tested your code. It's fine.
var a = {
"resultType" : "history",
"currentTime" : "2011-10-22T15:46:00+00:00",
"columns" : ["date","orders","quantity","low","high","average"],
"rowsets" : [
{
"generatedAt" : "2011-10-22T15:42:00+00:00",
"rows" : [
["2011-12-03T00:00:00+00:00",40,40,1999,499999.99,35223.50],
["2011-12-02T00:00:00+00:00",83,252,9999,11550,11550]
]
}
]
}
var util = require('util');
console.log(util.inspect(a.rowsets[0].rows, { showHidden: true, depth: null }));
Related
I'm a complete beginner to map-reduce and relatively new with MongoDB. I am trying to perform a map-reduce on a collection (by the name Customers).
My map function:
var map = function() {
emit(this.nationality, {edad: this.age, telefono: this.phone_number});
};
My reduce function:
var reduce = function(key, values) {
return Array.sum(values);
};
I call mapReduce() as follows:
db.Customers.mapReduce( map , reduce , { out : { inline : 1}} );
Finally my result field is:
"results" : [
{
"_id" : "Brazil",
"value" : {
"edad" : 34,
"telefono" : null
}
},
{
"_id" : "Colombia",
"value" : "[object BSON][object BSON]"
},
{
"_id" : "Germany",
"value" : {
"edad" : 18,
"telefono" : 2986
}
}, ...
As you can see it contains BSON objects, the problem being that I can't find a way to visualize the content of these BSONs, not even in Robomongo.
I have looked for other answers in Stackoverflow addressing this, so far I have found this:
"Your reduce function must return the same format that your map function emits". But being honest, I haven´t managed to figure out how do I apply it to solve my problem. I mean, what is the format of my emit? And in which format is the output of my reduce function?
If anyone could provide me the exact code lines, my gratitude in advance.
I'm new to Mongo and trying compare a array with a documents of collections and return list of matching records.
Let me explain:First Array
I have a collection (user) with following documents:
> db.user.find().pretty()
{
"_id" : ObjectId("57358220bf3e7d076b6ccdb1"),
"name" : "Sunny",
"phone" : "9417702107",
"email" : "ssdhiman07#gmail.com"
}
{
"_id" : ObjectId("57358242bf3e7d076b6ccdb2"),
"name" : "Pal",
"phone" : "9015719419",
"email" : "ss998#gmail.com"
}
{
"_id" : ObjectId("57358262bf3e7d076b6ccdb3"),
"name" : "viveky",
"phone" : "8826565107",
"email" : "sds998#gmail.com"
}
Second Array: i have a array of objects that is come from Http request below is structure of array.
{
"contacts" : [
{
"name" : "Sunny",
"phone" : "9417702107"
},
{
"name" : "Sukhpal",
"phone" : "9015719419"
},
{
"name" : "anurag",
"phone" : "9988776655"
},
{
"name" : "vivek",
"phone" : "8826565107"
}
]
}
Now I want to know which objects of Second Array are exists in First Array and which doesn't . Comparison should on basis of phone only . And in result i want same Array as Second Array but with one extra field that is
"exists":"true" or "exists":"false" . Something like this.
{
"contacts" : [
{
"name" : "Sunny",
"phone" : "9417702107"
"exists" :"true"
},
{
"name" : "pal",
"phone" : "90177668899"
"exists" :"false"
}
]
}
So for this i had tried something here is code of node.js with mongoos.
exports.matchcontacts = function(req, res, next)
{
var response = {};
var conArray = req.body.contacts;
var contact_list = [];
for(var i=0; i<conArray.length;i++)
{
var name = conArray[i].name;
var phone = conArray[i].phone;
Users.findOne({"phone":conArray[i].phone},function(err,data)
{
if(err)
{
response = {"error" : true,"message" : "Error fetching data"};
}
else if(!data)
{
contact_list.push({name:name,phone:phone,exists:"false"});
}
else
{
contact_list.push({name:name,phone:phone,exists:"true"});
}
});
}
response = {"error":false,"contacts":contact_list};
res.json(response);
};
But always got null {} empty result, and if i tried to get response inside Callback function then it return only single last compared value.
Problem is in first method is that callback function return result very late so result always empty .
and in second method loop override result and it also inefficient to use callback inside loop it will call no of time. So whole story i had explained
Now Please can anybody help me with code or suggest right way to get desired result thanks
Haven´t used mongodb, but the idea I would use is to first iterate your contacts and make a mapping of the phones to the corresponding object and mark them as non existent:
var obj = {};
for(var i=0; i<conArray.length;i++){
obj[conArray[i].phone] = conArray[i];
conArray[i].exists = false;
}
Then search in some way for the users that have those phones in your db, something like
var results = Users.find(records that have phone in Object.keys(obj) array)
Finally, you iterate your existant records and mark the corresponding contact
for(var i=0;i<results.length;i++){
obj[results[i].phone].exists = true;
}
I have some documents which are organized in a model tree structure (depth is variable!). Unfortunately some documents are missing and I need to find those broken chains. As you can see the last document in that chain has always the target field. This is the starting point and I have to look upwards using parent. The last element in that chain has always the field type.
{
"_id" : "K7NSxNEnNSr9nCszR",
"title" : "title",
"type" : "book",
"ancestors" : [ ]
}
{
"_id" : "diyvwYz66yoTCTt9L",
"field" : "something",
"parent" : "K7NSxNEnNSr9nCszR",
"ancestors" : [
"K7NSxNEnNSr9nCszR"
]
}
{
"_id" : "diyvwYz66yoTCTt9L",
"field" : "anything",
"target" : "D2YuXtM6Gzt4eWaW2",
"parent" : "QWvdAyftSGANM3zy8",
"ancestors" : [
"K7NSxNEnNSr9nCszR",
"QWvdAyftSGANM3zy8"
]
}
What I need to know is if any parent is missing or if the last element (=type existing) is missing.
var broken = [];
Collection.find({ target: { $exists: true }}).forEach(function(element) {
var startDocID = element._id;
if (Collection.find({ _id: element.parent }).count() === 0)
broken.push(startDocID);
});
console.log(broken);
But this isn't working well as I need to use a loop to get upwards until the top document (= type existing).
You're talking about recursion here if you need to go down the tree, so you probably need to write a recursive search function
var broken = [];
Collection.find({ target: { $exists: true }}).forEach(function(element) {
function recurse(e) {
var startDocID = e._id;
var nodes = Collection.find({ _id: e.parent });
if (node.count() === 0)
{broken.push(startDocID);}
else {
nodes.fetch().forEach(node) {
recurse(node)
}
}
recurse(element);
}
});
or something of that sort... (hard to debug without the data)
I am trying to add to an existing array in my mongoDB. Here is what I have, but it is of course incorrect because all the data gets wiped out after it tries to add it:
db.cardKeeper.update(
{_id: ObjectId('5621c5ac30895e5776e4d1ea')},
{
$push:{'cardKeeperApp.appData.cardDecks':deckObject}
}
)
deckObject which is the object I am trying to add to the array looks like this
var deckObject = {
name: productName,
searchName: productItem,
price:{
purchasePrice: productCost,
averageWorth: priceAverageFixed,
lowWorth: lowestSoldAmount,
highWorth: highestSoldAmount
}
}
and as you can see cardKeeperApp.appData.cardDecks is my array which holds more info that looks just like deckObject
If it helps here is the full object, I am trying to add to the cardDecks array. I have marked fields as null
{
"_id" : ObjectId("5635ddf82f4c220f4f932af2"),
"cardKeeperApp" : {
"appData" : {
"cardDecks" : [
{
"name" : "Some Name",
"searchName" : "Some+Name",
"price" : {
"purchasePrice" : null,
"averageWorth" : null,
"lowWorth" : null,
"highWorth" : null
}
}
],
"allDeckTotalWorth" : null
}
}
}
I found the solution. findAndModify by query:{_id:ObjectId} and then update and push:
db.cardKeeper.findAndModify({query:{_id: ObjectId('5635ddf82f4c220f4f932af2')},
update: {$push:{'cardKeeperApp.appData.cardDecks': deckObject}},
new:true}, function (err, doc) {
res.json(doc);
});
I have one tree-like structure containing block with certain id. Then I have another object, that contains 'id' : objectPart pairs.
Tree:
var tree = [
{
'property' : 'value',
'id' : 'someID',
//more properties...,
'content' : [
{
'prop' : 'something',
...
}
]
},
{
'prop' : 'val',
...
'content' : []
}
]
ID index:
{
'someID' : tree[0]
}
I need some way how when I do delete ID_index.someID, that object gets also deleted from main structure.
Structure after this code should look like this:
[
{
'prop' : 'val',
...
'content' : []
}
]
Instead of using delete you can write your own remove function. It should look like this:
function myRemove(stringId) {
delete ID_index[stringId]; //remove property from ID_index
objIndex = ... //find object index in tree array
tree.splice(objIndex, 1); //remove object from tree array
}