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.
Related
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
So I Have some data in my Mongo Database, which I.find() by express and send it to my EJS view. pretty simple. But the problem is when I try to read it using <pre><%=%></pre> i get undefined. Here's the entire code:
The Data Array containing Object in MongoDB:
[{
_id: 6069820f402d01120cda8cff,
imageName: 'Dining Plate',
imagePath: './public/assets/img/6.jpg',
description: 'Wallpapers',
__v: 0
}]
Express Code where I get it and send it to EJS:
app.get('/wallpapers/:id', ((req, res) => {
const urlID = req.params.id;
Thing.find({}, function (err, result) {
if (err) {
console.log(err);
} else {
var fres = result.filter(d => d._id == urlID);
res.render('wallpaper-page',{fres});
}
});
})
)
and the EJS:
<pre><%= fres.description%> %> </pre>
And Now the BIG CONFUSION: when I replace fres.description with fres._id, It works perfectly fine. but that's it, it doesn't wanna print any other key values. I've been searching far and wide for almost a day now. But nothing helps. this is annoying me now.
PS: console.log(fres.description) is undefined and console.log(fres._id) works fine.
Why? How do I fix this?
please tell me if you need any other code.
Besides the problem with the filter method returns an array, I think you have another problem accessing data from Mongoose response.
This problem is discussed here: Mongoose return data inside _doc object. You can check out my answer with a test code to demonstrate some methods to access data from Mongoose response.
Array.filter returns an array. So, var fres = result.filter(d => d._id == urlID); the variable fres is an array with an object in it.
And if you need only the object in your EJS template, you need to pass just that.
res.render('wallpaper-page',{fres: fres[0]});
Now you can access the description key directly. But I don't understand how fres._id works, it should also be undefined.
I have a project where I have to process an input CSV file and store it into an array that I can add to, then print it out into a CSV file. I then use the transaction data for the rest of my project so being able to complete this part is vital as testing will be performed with other CSV files.
My issue is that whilst using csv-parse if I use console.table(results); it shows the csv objects when I run the .js file in my command terminal so I know its parsing but no matter what I do I cannot get the objects to go into my array variable.
console.table(results);
Please can someone give me a hint as to where I've gone wrong:
var fs = require('fs');
var parse = require('csv-parse');
var transactionValues = []; //Need an array to hold transactions
//constuctor for transactions
function addData (id, accountType, initiatorType, dateTime, transactions) {
var data = {
"AccountID" : id,
"AccountType" : accountType,
"InitiatorType" : initiatorType,
"DateTime" : dateTime,
"TransactionValues" : transactions
}
transactionValues.push(data); //should add a new line
}
var parser = parse({columns: true}, function (err, results) {
console.table(results);
addData(results.index[0].AccountID, results.index[0].AccountType, results.index[0].InitiatorType, results.index[0].DateTime, results.index[0].TransactionValue, 0);
}); //attempted to save the objects into the array but no success
fs.createReadStream(__dirname+'/testData/customer-1234567-ledger.csv').pipe(parser)
console.log(transactionValues); // array is empty
I believe results is already a normal array as it comes back from csv-parse. You are trying to access the first element with results.index[0], but it would just be results[0]. Another issue is that fs.createReadStream(...).pipe(...) is asynchronous. That means your console.log will run before it is done parsing. You would need to put any code that has to run after parsing in the callback of your parse function. Something like this:
var parser = parse({columns: true}, function (err, results) {
console.table(results);
for (const row of results) { //loop through each object parsed from the csv
addData(row.AccountID, row.AccountType, row.InitiatorType, row.DateTime, row.TransactionValue, 0);
}
console.log(transactionValues); // this should be populated properly
/* Do anything that needs to use transactionValues here */
});
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.
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);
}
});