Storing MongoDB document inside a Node.js array - javascript

Apologies in advance for what is undoubtetly a silly question.
I'm trying to store the raw JSON documents from MongoDB inside a Node.js array. The following code gives me an atrocity of JSON inside an array, inside a string, inside an array.
let subscriptions = [];
MongoClient.connect(mongourl, function(err, db) {
if (err) throw err;
var dbo = db.db("sigdb");
dbo.collection("customers").find({}).project({ _id: 0 }).toArray(function(err, result) {
if (err) throw err;
subscriptions.push(JSON.stringify(result));
db.close();
});
});
I have tried to exclude toArray(), using the syntax of findOne() - no luck. Declaring subscriptions as a standard variable only returned undefined. Not putting result through JSON.stringify() made the second part of the document appear as [Object].
Any suggestions on how to untangle this and just have JSON stored in an array would be much appreciated.
Edit: turns out that instead of subscriptions.push(result) I could just use subscriptions = result.

Related

Confusing error message using updateOne() function on a mongodb collection

To summarize, I have a mongodb database with a 'groupcollection' in it. One of the attributes is called 'deleted' and it has values either true or false. I want to update the value of 'deleted' for a specific document using 'groupname' as the query attribute. However, when I try the code below I receive the error "TypeError: collection.updateOne is not a function"
router.post('/deletegroup', function(req, res) {
var db = req.db;
var collection = db.get('groupcollection');
var filter = {"groupname" : req.body.groupname};
var updates = { $set: {"deleted" : true} };
collection.updateOne(filter, updates, function(err) {
if (err) {
// If it failed, return error
res.send("There was a problem deleting the group from the database.");
}
else {
// And forward to success page
res.redirect("grouplist");
}
});
});
I've read the documentation on updateOne() for Node.js from mongoDB and I can't seem to figure out the reason for the error. Also, I am still very new to javascript/nodejs/mongo so I would greatly appreciate more informative answers!
The solution I came up with was using unique IDs for each group and instead of using updateOne() just using update() and having the unique ID as the query to make sure that I don't modify groups with the same name

Unable to mutate Array in node JS mongo db

I am using rest API of node with mongodb and I am getting some error like
I am unable to mutate array arr when it's push in that response function.
every time I got an empty array in it.
What im using:
var arr = [];
Business.find({ userId: userId }, (err,docss)=>{
if(err) throw err;
arr.push(docss)
});
console.warn(arr)
OUTPUT : []
thanks in advance for helping.

Unable to see any callback when querying Neo4j from Node.js

I send a query from Node.js to Neo4j, but I do not see anything callback. The query is correctly executed but I am unable to see any information i nthe callback and log it in the console.
I think node.js executes console.log before any data has come, but I do not know how to solve it.
Node.js:
// Load Modules
var neo4j = require('neo4j');
// Database Connection
var db = new neo4j.GraphDatabase("http://neo4j:Gemitis26#localhost:7474/");
// Inizialize Query
var query = "CREATE (:Song {name:'James'})";
db.cypher(query, function(err, node){
if(err) throw err;
// Output node properties.
console.log(node.data);
// Output node id.
console.log(node._id);
});
Output:
C:\Users\RRamos\Documents\Projects\test-neo4j>node index.js
[]
undefined
As I said, I check it and it is correctly created.
There are a number of problems in your code:
Your Cypher query does not have a RETURN clause so your query response will always be an empty array (because it will never contain any result rows).
Your callback is expecting to wrong data structure for the response.
Try this code. It dumps out the error (if any) and the response, so that you can see the actual data structure of a response. It also uses a for-loop to iterate through the rows of data in the response and print out each s node's properties and its native ID. In your case, there will only be at most one result row, so the loop is not strictly necessary, but in general there can be multiple rows.
// Load Modules
var neo4j = require('neo4j');
// Database Connection
var db = new neo4j.GraphDatabase("http://neo4j:Gemitis2#localhost:7474/");
// Inizialize Query
var query = "MATCH (s:Song {name:'James'}) RETURN s";
db.cypher(query, function(err, res){
// Dump out the err and response, to see the data structure.
console.log("err: %j, res: %j", err, res);
if(err) throw err;
// Print out the data for each row in the response.
for (var i = 0; i < res.length; i++) {
var s = res[i].s;
// Output node properties.
console.log(s.properties);
// Output node id.
console.log(s._id);
}
});

Using mysql node.js driver to get an entire database as JSON

I'm working on creating a JavaScript file to get a JSON dump of an entire MySQL database, running on server side. I found and am using the MySQL driver for node.js (https://www.npmjs.com/package/mysql) for queries, it's been straight forward enough to start. My issue is that I need to call multiple queries and get the results from all of them to put into a single JSON file and I can't quite get that to work. I'm entirely new to JavaScript (basically never touched it before now) so it's probably a relatively simple solution that I'm just missing.
Currently I do a query of 'SHOW TABLES' to get a list of all the tables (this can change so I can't just assume a constant list). I then just want to basically loop through the list and call 'SELECT * from table_name' for each table, combining the results as I go to get one big JSON. Unfortunately I haven't figured out how to get the code to finish all the queries before trying to combine them, thus retuning 'undefined' for all the results. Here is what I currently have:
var mysql = require('mysql');
var fs = require('fs');
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'pass',
database: 'test_data'
});
connection.connect();
connection.query('SHOW TABLES;', function(err, results, fields)
{
if(err) throw err;
var name = fields[0].name;
var database_json = get_table(results[0][name]);
for (i = 1; i < results.length; i++)
{
var table_name = results[i][name];
var table_json = get_table(table_name);
database_json = database_table_json.concat(table_json);
}
fs.writeFile('test_data.json', JSON.stringify(database_json), function (err)
{
if (err) throw err;
});
connection.end();
});
function get_table(table_name)
{
connection.query('select * from ' + table_name + ';', function(err, results, fields) {
if(err) throw err;
return results;
});
}
This gets the table list and goes through all of it with no issue, and the information returned by the second query is correct if I just do a console.log(results) inside the query, but the for loop just keeps going before any query is completed and thus 'table_json' just ends up being 'undefined'. I really think this must be an easy solution (probably something with callbacks which I don't quite understand fully yet) but I keep stumbling.
Thanks for the help.
I'm guessing that this is for some sort of maintenance type function and not a piece that you need for your application. You're probably safe to do this asynchronously. This module is available here: https://github.com/caolan/async
You can also use Q promises, available here: https://github.com/kriskowal/q
This answer: describes both approaches pretty well: Simplest way to wait some asynchronous tasks complete, in Javascript?

Uncaught MongoError: unrecognized field 'allowDiskUsage'

I installed 2.5.5 so that I can try the new "$out" operator to create new collections with aggregation results. My node adapter is mongodb#1.3.23. I don't have "allowDiskUsage" in my code, but I get this error:
Uncaught MongoError: unrecognized field 'allowDiskUsage'
What do I need to do to update my project to run 2.5.5?
From a simple test on the same driver version I do not see the same results:
var MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://localhost/test', function(err, db) {
if (!err) {
db.collection('data', function(err, collection) {
if (!err) {
collection.aggregate([
{$out: "another" },
],function(err, result) {
if (err) {
console.log(err);
}
db.close();
});
}
});
}
});
There is an option for allowDiskUse that can be passed to the runCommand call to aggregate, but this does not directly have an impact on the $out pipeline operator, as it is intended for allowing the stages to use disk storage rather than memory alone. The usage of $out as you will be aware is to put the results in an output collection rather than return a cursor object.
If the same code used by itself is causing the same problem, you should check your installed driver version. As of 1.3.23 with a MongoDB 2.5.5 server, this code works as expected.
If this code passes, then there is likely some call or overriding module in your project that is implementing the option you specify in the error.

Categories