Node CSV Parser output issue - parsing

I am trying to use Node CSV Parser to read in a query result from my Mongo database and write it out to a csv file.
When I run my script, I get a csv file with two [object] entries on the first line and everything else blank.
This is my code:
// node samples/sample.js
var csv = require('csv');
var mongoose = require('mongoose');
var User = require('../models/userModel').User;
dsn = "mongodb://localhost/test";
mongoose.connect(dsn);
console.log ("here");
var users = User.find({}, function(err, result){
console.log(result);
});
var columns = ['userName','agencyName','email','password','id'];
csv()
.from(users, {
columns: true
})
.toPath(__dirname+'/users.csv',{
columns: ['userName','agencyName','email','password','id']
})
.transform(function(data){
data.unshift(data.pop());
return data;
})
.on('data',function(data,index){
console.log('#'+index+' '+JSON.stringify(data));
})
.on('end',function(count){
console.log('Number of lines: '+count);
})
.on('error',function(error){
console.log(error.message);
});
This is the data displayed in terminal:
[ { userName: 'LasVegas',
agencyName: 'City of Las Vegas',
email: 'lasvegas#gmail.com',
password: 'upload1',
_id: 4ffe2e6bddc0c02b15000001 } ]
I have only entered one user into the database so I believe it is correct.
Any help would be greatly appreciated!
EDIT:
Here is my code after trying to call csv in the callback:
// node samples/sample.js
var csv = require('csv');
var mongoose = require('mongoose');
var User = require('../models/userModel').User;
dsn = "mongodb://localhost/test";
mongoose.connect(dsn);
console.log ("here");
var columns = ['userName','agencyName','email','password','id'];
var users = User.find({}, function(err, result){
console.log(result);
if (err){
callback(err,null);
}else{
csv()
.from(users, {
columns: true
})
.toPath(__dirname+'/users.csv',{
columns: ['userName','agencyName','email','password','id']
})
.transform(function(data){
data.unshift(data.pop());
return data;
})
.on('data',function(data,index){
console.log('#'+index+' '+JSON.stringify(data));
})
.on('end',function(count){
console.log('Number of lines: '+count);
})
.on('error',function(error){
console.log(error.message);
})
}
});
Now instead of two [object] fields, the fields contain weird symbols and I am asked to choose a filter when opening the file.

Your call to User.find() is asynchronous; it's not assigning the results of the search to users. You need to move your call to csv into the callback and either replace the reference to users there with results or rename the callback parameter to users.

Related

Trying to Script a Search Result into a Netsuite Entity Field

Having two issues with this. One is that I keep getting an error when trying to upload my script. The other is that one version that I did get to upload, didn't load any value into the field (ie. field blank after script ran)
The error I keep getting on upload is "Fail to evaluate script: All SuiteScript API Modules are unavailable while executing your define callback." And although I've made drastic changes to the script, it still won't allow me to upload.
/**
*#NApiVersion 2.x
*#NScriptType ScheduledScript
*/
define(['N/search', "N/record"],
function(search, record) {
function loadAndRunSearch(scriptContext) {
var mySearch = search.load({
id: 'customsearch1088'
});
mySearch.run().each(function (result) {
var countt = result.getValue({
name: 'number'
});
var entity = result.getValue({
name: 'internalid'
});
var objRecord = record.load({
type: record.Type.CUSTOMER,
id: entity,
isDynamic: true,
});
var vfield = objRecord.getField({
fieldId: 'custentity_orders_12m'
});
objRecord.setValue({fieldId: 'custentity_orders_12m', value: countt});
objRecord.save();
});
}
return {
execute: loadAndRunSearch
};
});
That's the script stripped down to the bare bones (FYI still doesn't upload), and the script that uploaded was basically a more complicated version of the same script, except it didn't set the field value. Can anyone see where I've gone wrong?
You haven't returned the entry function.
/**
*#NApiVersion 2.x
*#NScriptType ScheduledScript
*/
define(['N/search', 'N/record'],
function(search, record) {
function loadAndRunSearch(scriptContext) {
var mySearch = search.load({
id: 'customsearch1088'
});
mySearch.run().each(function (result) {
var countt = result.getValue({
name: 'number'
});
var entity = result.getValue({
name: 'internalid'
});
record.submitField({
type: record.Type.CUSTOMER,
id: entity,
values: {
'custentity_orders_12m' :countt
}
});
});
}
return {
execute : loadAndRunSearch
}
});

Ionic v1 /Angular JS slow rendering views when use Sqlite plugin

I developing an application using ionic1 and AngularJS.When i want to go back to previous view i must save some data into sqlite database using sqlite plugin from https://github.com/litehelpers/Cordova-sqlite-storage.git.When i press button to go back i see a lag when it pass from a view to another.The sqlite table structure have two columns:
->Id -primary key -integer
->data-string
In this table i want to save data field as string(from json).
Does anyone knows how to make this process faster? I'm using an iPad for testing.
I'm posting my code here to show how save function is implemented.Thanks for any help. :)
$scope.storeProfileDataCourses = function(data) {
console.log('insertData');
var querySelect = "SELECT * FROM Table where Id=?";
$cordovaSQLite.execute(db, querySelect, [crewId]).then(function(res) {
console.log('Rows:' + res.rows.length);
if (res.rows.length > 0) {
var queryUpdate = "UPDATE Table SET data=? WHERE Id=?";
$cordovaSQLite.execute(db, queryUpdate, [JSON.stringify(data), crewId]).then(function(res) {
console.log('update');
console.log(res);
}, function(err) {
console.error(err);
});
} else {
console.log('Need to insert');
var query = "INSERT INTO Table(Id,data) VALUES (?,?)";
$cordovaSQLite.execute(db, query, [Id, JSON.stringify(data)]).then(function(res) {
console.log("INSERT ID -> " + res.insertId);
}, function(err) {
console.error(err);
});
}
});
}

How do I tie an image stored in Firebase Storage to a record in Firebase Database? *SWIFT/iOS* [duplicate]

I have a marketplace web app, where users can upload items, and of course they can also see images associated with these items. The problem is organizing the storage buckets, I was thinking to make the path itemImages/itemUID/image1.jpg. The problem is getting the itemUID, which is automatically generated, after an item is added to the database.
Here's a code snippet I have for adding items to the db:
itemsRef.push({
title: title,
description: description,
tags: tags,
price: price,
});
and here's a simplified function I use to store an image:
var uploadTask = imageNewItemRef.child('fakeUID' + '/' + imageNames[x]).putString(images[x], 'base64');
uploadTask.on('state_changed', function(snapshot) {
}, function(error) {
console.log("error uploading image");
}, function() {
var downloadURL = uploadTask.snapshot.downloadURL;
console.log(downloadURL);
});
as you can see, I'm using a hardcoded fakeUID link for testing purposes, but I have no clue (and searching hasn't helped), on how to have a uniqueUID instead of a fake one, that is linked to the item :/
Any help is appreciated!
Apologies for poorly written (and untested) JS, but would something like this work?
// create a new push ID and update the DB with some information
var currentItemRef = itemsRef.push({
title: title,
description: description,
tags: tags,
price: price,
}).then(function() {
var storageRef = firebase.storage().ref();
// currentItemRef.name is the unique key from the DB
return storageRef.child(currentItemRef.name + '/' + imageNames[x]).putString(images[x], 'base64');
}).then(function(snapshot) {
// update the DB with the download URL
return currentItemRef.update({
url: snapshot.metadata.downloadURLs[0]
});
}).catch(function(error) {
console.error(error);
});

Webix mobile calendar saving events to mysql database twice

So am experimenting with Webix and so far I like it. Am playing around with the mobile calendar/scheduler and am getting stuck with saving new events into mysql database. I have followed the tutorials and docs about saving data to the database and indeed I am able to save new events. Problem is that it is saving the new events twice, and I have failed to figure out why. Here is the code:
webix.ready(function(){
webix.ui.fullScreen();
webix.ui({
rows:[
{
view: "toolbar", id:"toolbar", elements:[
{
view: "icon", icon: "bars",
click: function(){
if( $$("menu").config.hidden){
$$("menu").show();
}
else
$$("menu").hide();
}
},
{
view: "label",
label: "JPlan"
}
]
},
{
view: "scheduler",
id: "scheduler",
url: "data/getEvents.php",
save:{
"insert":"data/saveEvents.php",
"update":"data/update.php",
"delete":"data/delete.php"
}
}
]
});
});
And the php code to save the new events:
<?php
include('mysql.class.php');
$db = new MySQL();
$values = array();
$now = time();
$values["eventTitle"] = MySQL::SQLValue($_POST['text']);
$values["eventJudge"] = MySQL::SQLValue($_POST['judge']);
$values["eventStart"] = MySQL::SQLValue($_POST['start_date']);
$values["eventEnd"] = MySQL::SQLValue($_POST['end_date']);
$values["eventNotes"] = MySQL::SQLValue($_POST['details']);
$values["eventAddedTime"] = MySQL::SQLValue($now);
$values["eventAddedBy"] = MySQL::SQLValue('');
// Execute the insert
$result = $db->InsertRow("tbl_events", $values);
?>
The app loads all events from the database well. It is just that when I save a new event, it saves the evet twice in the database. I have not yet worked on the update and delete code.
Any help?
Client side code expects some valid JSON response from a server-side, as confirmation that the save operation was successful. Otherwise, a client-side code may make another attempt to save a data.
$result = $db->InsertRow("tbl_events", $values);
$id = get_id_of_new_record();
echo "{ id: $id }";

How to create a join table using sequelize and sqlite?

I am trying to establish a many-to-many relationship between tables in sqlite using sequelize.
I want to add records to a join table (assign tasks to a user) and retrieve data from that table. For some reason, this does not work. Here is my code:
var orm = new Sequelize('db_name', '', '', {
dialect: 'sqlite',
storage: path.join(__dirname, 'db_name')
});
var User = orm.define('User', {
username: {type: Sequelize.STRING, unique: true}
});
var Task = orm.define('Task', {
id: {type: Sequelize.STRING, unique: true},
taskName: Sequelize.STRING
});
Task.hasMany(User);
User.hasMany(Task);
Task.sync();
User.sync();
Having read documentation (http://sequelize.readthedocs.org/en/latest/api/associations/#hasmanytarget-options), I expect that a join table TasksUsers should be created. I also expect .addTask method do be available. Then in another file I have:
db.User.findOrCreate({where:{username: "fakeUser"}}); //this seems to work
//some code to populate "Tasks" table;
db.User.find({where: {username: "fakeUser"}}).
complete(function(err,user){
console.log("user", user); //the user is found
db.Task.find({where: {id: "some_value"}}).
complete(function(err, task) {
console.log("task", task); //the task is found, so it works up to this point
user.addTask(task). //this line does not work
complete(function(err, results){
console.log("posting error", err);
});
})
});
I get an error "Possibly unhandled SequelizeDatabaseError: Error: SQLITE_ERROR: no such table: TasksUsers". The user.getTasks() method (without any arguments in the parentheses) does not work for the same reason.
Another observation: for testing purposes, I added these lines of code after establishing hasMany relationships:
orm.query("SELECT name FROM sqlite_master WHERE type = 'table'").success(function (res) {
console.log("tables", res);
})
The result that I get is tables [ 'Tasks', 'Users' ]
The versions: sequelize 2.0.0-rc2, sqlite3 3.0.4. I would be very grateful for any help.

Resources