Here i have upload my excel file, now i need to convert it to json,but it's showing the following error:
TypeError: Cannot set property length of [object Object] which has only a getter
Here is my code:
//other module dependencies also given
var converter = require('xls-to-json')
var Data = {};
exports.fnup = function(req, res) {
var upfile = req.file;
var userid = req.body.userid || '0';
if (uploafile.fieldname !== 'myFile') {
return res.status(400).send({
message: 'Please upload '
});
}
converter({
input: './foldern1/' + upfile.originalname,
output: null
},
function(err, results) {
console.log("hheeelo");
if (err) {
console.log('Error:', err);
} else {
console.log("suvbb", results);
Data = _.filter(results, function(result) {});
}
});
};
_.filter only works with an Array, not an Object. results is an Object.
Related
i know this question may be asked about 1000 times here but i cant find the error in my script.
I am trying to iterate through 2 arrays to get a name from an city_id and an organisation_id in a each() loop. i would like to write there values to the "mother"-object to get all informations in one place. Here is the code i've written so far:
let express = require('express');
let router = express.Router();
let request = require('request');
let connection = require('../lib/mysql');
router.get('/', function(req, res) {
if(req.session.loggedin === true){
getList((err, finlist) => {
console.log(finlist)
});
} else {
const cssPath = '/stylesheets/style.css'
res.render('login', { cssPath, title: 'Login' });
}
});
function getList(callback) {
var result = [];
connection.query('SELECT * FROM lists ', (err, rows) => {
if(err) throw err;
var r=0;
rows.forEach(function(item) {
result[r] = item;
getCities((err, cty) => {
result[r].city = cty[item.city_id].name;
getOrganisations((err, org) => {
result[r].organisation = org[item.organisation_id].name;
});
callback(result);
});
r++;
});
});
}
function getCities(callBack) {
var result=[];
connection.query('SELECT * FROM cities ', (err, rows) => {
if (err) throw err;
rows.forEach(function (cty) {
result[cty.id] = cty;
});
if (err) {
callBack(err, null);
} else {
callBack(null, result);
}
});
}
function getOrganisations(callBack) {
var result=[];
connection.query('SELECT * FROM organisations ', (err, rows) => {
if(err) throw err;
rows.forEach(function(org) {
result[org.id] = org;
});
if (err) {
callBack(err, null);
} else {
callBack(null, result);
}
});
};
module.exports = router;
I always get the error
TypeError: Cannot set properties of undefined (setting 'city')
at /opt/alarmprocessor/routes/settings.js:53:32
. . .
which is the line result[r].city = cty[item.city_id].name;
King regards for helping me out :)
Tried to set it as an array, as an Object, made console outputs everywhere... seems all to be fine.. Maybe i am too new to NodeJS so it hasnt been clicked in my Head ;D
This error occur because result[r] doesn't exist line 53. It's declared but doesn't "exist" -> it's undefined. If you perform a mere console.log(result[r]); line 52 you will get an undefined, and you can't set properties (like city) to an undefined value.
The quick fix would be to use optional chaining like this:
result[r]?.city = cty[item.city_id].name;
it won't fix your code, it will only stop crashing by ignoring the assignment.
want to save csv file in mongodb with node js i used javascript to to add and fetch data but it get error
get('/import', function(req, res, next) {
var stocks1 = [];
var csvStream = csv()
.on("data", function(data){
// var errorCount = 0;
// var csvStream = csv.parse({strictColumnHandling: true, headers: true}) .on("data", function(data){
var item = new Stock({
Diamondcode: data[0],
Sortdesc: data[1],
Colour: data[2],
Size: data[3],
Meserment:data[4] ,
Price:data[5]
});
item.save(function(error){
console.log(item);
if(error){
throw error;
}
});
}).on("end", function(){
console.log(" End of file import");
});
// stream.pipe(csvStream);
res.json({success : "Data imported successfully.", status : 200});
}).get('/fetchdata', function(req, res, next) {
Stock.find({}, function(err, docs) {
if (!err){
res.json({success : "Updated Successfully", status : 200, data: docs});
} else {
throw err;
}
});
That is because you haven't given the path of your CSV. One traditional way I used in my node projects as
kept route file different and pass your csv file in form data and then access it as req.files.
Make sure you create a wrapper for your CSV conversion
I have a function in a utils file that I want to call and assign the exported result to a variable.
Currently, the variable is defined then I try to assign the return result but I am getting undefined as the result when I console.log it.
Here is my utils/consul file
var consul = require("consul")({host: config.consul.host'});
var consulBase = [];
var options;
module.exports = {
consulQuery: function(service){
consul.catalog.service.nodes(service, function(err, results) {
if(err) {console.log(err); throw err;}
if(results.length <= 0) return {message: `Error could not find any service of ${service} registered with consul,`, errorCode: 500};
if(results.length > 0) consulBase = [];
results.forEach((result) => {
consulBase.push(result.ServiceAddress+ ':' +result.ServicePort);
});
var serviceURL = 'http://' + consulBase[Math.floor(Math.random()*consulBase.length)];
return options = {
baseUrl : serviceURL,
form: {'':''},
headers: {authorization: ''}
};
});
}
Then in another file, I am calling like this and then trying to assign the value to 'options' but am getting undefined.
var consulQuery = require("../utils/consul").consulQuery;
// Get options array right away
var options = consulQuery('auth');
// Get options array every 5 seconds
setInterval(() => {
options = consulQuery('auth');
console.log(options);
}, 5 * 1000);
OK you have a couple issues.
First, is conceptual about what you are trying to do. Second is what do you actually need to change in your code to make it work.
I will not talk about the first part because, and there are plenty of good resources to learn about async with examples better then I can do here.
For the actual problems with your code:
You are missing a callback for consulQuery()
It should be something like this (notice the cb i added):
module.exports = {
consulQuery: function (service, cb) {
consul.catalog.service.nodes(service, function (err, results) {
if (err) {
console.log(err);
cb(err, null)
throw err;
}
if (results.length <= 0) return {
message: `Error could not find any service of ${service} registered with consul,`,
errorCode: 500
};
if (results.length > 0) consulBase = [];
results.forEach((result) => {
consulBase.push(result.ServiceAddress + ':' + result.ServicePort);
});
var serviceURL = 'http://' + consulBase[Math.floor(Math.random() * consulBase.length)];
cb(null, {
baseUrl: serviceURL,
form: {'': ''},
headers: {authorization: ''}
});
});
}
}
Second, in the other file in which you invoke the function, you will have to now pass a callback function.
options = consulQuery('auth', (err, response) => {
if(err){
console.log(err)
}
console.log(response)
});
When creating new document in node js gives MongoError of write ECONNRESET.
Following is the error in console when creating the new document:
error: Error adding new agreementTemplate ! Error :
{"name":"MongoError","message":"write ECONNRESET"}
following is the controller function creating the error.
function addSubChapter(req, res) {
logger.debug('Processing request for creating a new agreement.');
console.log(req.body);
async.waterfall([
function (callback) {
agreementService.getAgreementTemplate( callback);
},
function (data, callback) {
agreementTmplService.AgreementTemplateSetDefaultFalse(function(err, result){
callback(null, data);
});
},
function (data, callback) {
var agreementTemplate =data.result[0];
var chapter ={
name: req.body.name
}
agreementTemplate = agreementTemplate.toObject(); // swap for a plain javascript object instance
delete agreementTemplate["_id"];
agreementTemplate.createdBy= req.body.user;
agreementTemplate.created= new Date();
//agreementTemplate.Chapters.push(chapter);
var chapters = agreementTemplate.Chapters;
for(var i=0;i<chapters.length; i++){
if(chapters[i].name == req.body.chapter){
var subChap ={
name: req.body.name
}
chapters[i].subChapters.push(subChap);
}
}
console.log('----------------------');
console.log(agreementTemplate);
agreementService.createAgreementTemplate(agreementTemplate, callback);
},
function (data, callback) {
agreementTmplService.addSubChapter(req.body, callback);
}
], function (err, result) {
utils.processResponse(err, result, res);
});
}
When creating the agreement template it causes the error, here is the service function:
function createAgreementTemplate(data, callback) {
serviceHelper.createModel(AgreementTemplate, 'agreementTemplate', data, callback);
}
and the createModel function is as follows.
function createModel(model, modelName, modelData, callback) {
logger.debug('Creating new Model : %s', modelName);
var modelObj = model(modelData);
modelObj.save(function (err, newModelObj) {
if (err) {
logger.error('Error adding new %s ! Error : %s', modelName, JSON.stringify(err));
callback(utils.handleMongodbError(err), null);
} else {
logger.info('New Model of type : %s created with id : %s', modelName, JSON.stringify(newModelObj._id));
var result = {};
result.status = httpStatus.OK;
result.result = newModelObj._id;
callback(null, result);
}
});
}
I'm trying to return the JSON data in a mongoose document, and then display it using Angular. There's no errors on the page when using this code. The $http.get method in the Angular IndexCtrl never makes it to success, which leads me to believe the problem is how I'm implementing the API get method. Any help rewriting that method to return properly greatly appreciated!
To clarify: what I want is to be able to access the document like a JSON Object so I can display the data to the client.
update: it does produce the error:
GET http://localhost:3000/api/tracks
It takes a while for that error to show in the console
the api method
app.get("/api/tracks", function(req, res) {
return Track.find({}, function (err, tracks) {
if (err) {
res.send(500);
return;
}
return res.json({
tracks: tracks
});
});
});
the mongoose database
var mongoose = require('mongoose');
var uristring =
process.env.MONGOLAB_URI ||
'mongodb://localhost/HelloMongoose';
var mongoOptions = { db: { safe: true }};
var db = mongoose.createConnection(uristring, mongoOptions, function (err, res) {
if (err) {
console.log ('ERROR connecting to: ' + uristring + '. ' + err);
} else {
console.log ('Succeeded connected to: ' + uristring);
}
});
//a Schema for a track
var Schema = new mongoose.Schema({
name: String,
location: String,
description: String
});
var Track = mongoose.model('Track', Schema);
var spot = new Track({name: 'zildjian'});
spot.save(function (err) {
console.log('saved');
if (err) // ...
console.log('meow');
});
The Angular controller
function IndexCtrl($scope, $http) {
$http.get('/api/tracks').
success(function(data, status, headers, config) {
$scope.tracks = data.tracks;
console.log($scope.tracks + "scope tracks data"); //This does not log! it never makes it this far
});
}
The Jade template that displays $scope.tracks
p There are {{tracks.length}} posts
div(ng-repeat='track in tracks')
h3 {{track.name}}
div {{track.description}}
I was not pulling the entries from the model correctly. Here is how I fixed it:
app.get("/api/tracks", function (req, res) {
var track = [];
var Track = mongoose.model('Track', trackSchema);
Track.find({}, function (err, records) {
records.forEach(function (post, i) {
track.push({
id: i,
title: post.title,
text: post.text.substr(0, 50) + '...'
});
});
res.json({
track: track
});
});
};
}