I am creating a command line app using nodejs. For some reason whenever I enter a track (node liri.js spotify-this-song "enter track") i get a response of a random band called Nocturnal rites, song named "something undefined", and album called "grand illusion". Does anyone know where I am wrong, or why I am getting these responses?
function spotifyIt(song) {
spotify.search({ type: 'track', query: song }, function(err, data) {
if ( err ) {
console.log('Error occurred: ' + err);
return; //from spotify npm docs
}
else{
var songInfo = data.tracks.items[0];
var songResult = console.log(songInfo.artists[0].name)
console.log(songInfo.name)
console.log(songInfo.album.name)
console.log(songInfo.preview_url)
console.log(songResult);
};
});
}
Nevermind, I figured it out. had to change the query to the correct params[]... i.e it ended up looking like this
function spotifyIt() {
spotify.search({ type: 'track', query: params[1] }, function(err, data) {
if ( err ) {
console.log('Error occurred: ' + err);
return; //from spotify npm docs
}
else{
var songInfo = data.tracks.items[0];
var songResult = console.log(songInfo.artists[0].name)
console.log(songInfo.name)
console.log(songInfo.album.name)
console.log(songInfo.preview_url)
console.log(songResult);
};
});
}
I had a global variable var params = process.argv.slice(2); and a switch statement with another params[1], so that it ended up calling the fourth parameter i.e. where the song title was named in the terminal
switch(params[0]) {
case "my-tweets":
myTweets();
break;
case "spotify-this-song":
if(params[1]){ //if a song is put named in 4th paramater go to function
spotifyIt();
} else { //if blank call it blink 182's "whats my age again"
spotifyIt("What\'s my age again");
}
break;
Related
I am trying to remove a record from MongoDB using nodeJS. But the record is not getting deleted.
Please find the below code:
exports.remove = function(studentId, cb) {
var collection = db.get().collection('students');
collection.remove({_id: studentId}, function(err) {
if (err) {
throw err;
}
else {
cb(err);
console.log("Record deleted.");
}
});
}
I have tried the studentId with ObjectID() as below:
exports.remove = function(studentId, cb) {
var collection = db.get().collection('students');
collection.remove({_id: new mongodb.ObjectID(studentId)}, function(err) {
if (err) {
throw err;
}
else {
cb(err);
console.log("Record deleted.");
}
});
}
But getting an error as :
"Error: Argument passed in must be a single String of 12 bytes or a string of 24 hex characters"
Please help on this issue!!!!!
When you call your remove function, make sure you are passing an actual string as the first argument, not a numeric.
Or, in your remove function, cast studentId to a string like so:
collection.remove({_id: studentId.toString()}, function(err) {...
at first, you should remove unnecessary get() method on db:
var collection = db.collection('students');
next step, don't dismiss new keyword, it's just fine to only wrap:
collection.remove({_id: mongodb.ObjectID(studentId)}, function(err) {
perhaps creating the id from this method will help :
mongodb.ObjectID.createFromHexString(studentId);
https://mongodb.github.io/node-mongodb-native/api-bson-generated/objectid.html
I got the solution for this, why I was getting the error - "Error: Argument passed in must be a single String of 12 bytes or a string of 24 hex characters" when using new mongodb.ObjectID(studentId). I want this to be shared with all of us.
My angularJS controller is as follows:
mainApp.controller("deleteStudentController", function($scope,$http) {
var resData = {};
$scope.student = {};
var urlGet = "/students/all";
$http.get(urlGet)
.then(function(response) {
$scope.students = angular.fromJson(response.data);
});
$scope.deleteStudent = function(){
var urlDelete = "/students/remove:"+$scope.studentRadio;
$http.delete(urlDelete)
.success(function(response, status, headers, config){
$scope.output = "Student successfully deleted.";
})
.error(function(response, status, headers, config){
$scope.output = "Error in processing. Please try again.";
});
}
});
In the above controller we can see the URL as
var urlDelete = "/students/remove:"+$scope.studentRadio;
which inturn calls my node controller :
router.delete("/remove:studId", function(req,res){
Students.remove(req.params.studId, function(err) {
if (err) {
throw err;
}
else {
var respOut = "Student deleted";
res.send(respOut);
}
});
});
The Angular code is setting the endpoint like this:
"/students/remove:"+$scope.studentRadio
I want the : to be there, so the URL will look something like this:
/students/remove:576c1d4781aaa4f16a68af24
The Express route is as below:
router.delete("/remove:studId", ...)
: is a special character in Express routes (it declares a named parameter called studId). This means that the route will take everything after /remove to be the value of studId, including the colon that's in the URL. So req.params.studId is :576c1d4781aaa4f16a68af24, which has a length of 25 characters.
If we want to use this sort of URL scheme, we need to make the colon to be part of the match by escaping it (so it loses its special meaning):
router.delete("/remove\::studId", ...)
I am a little confused about the return value of Mongoldb update and how should I handle error with it.
I am using Node.js, Express.js and Mongoose.js as my Mongodb driver
As I look through many tutorial, the only way of error handling I saw is ...
Example: A simple user schema .. and I want to update telephoneNumber
Users
{
email : abc#abc.com,
telephoneNumber : 123456
}
Example of error handling written in node.js that many tutorial taught me
Users.update({email: abc#abc.com}, {'$set': {telephoneNumber : 654321}, function(err, result){
if(err){
//err
}else if(!result){
//update not success
}else{
//update success
}
});
but as I look through Mongodb documentation, I found out that update return WriteConcern value, which return something like this
{
"ok" : 1, // update with no err
"nModified" :1, // successfully update 1 user
"n" : 1 // found 1
}
So my question is, should I handle my error like this instead, so I would know more about the failures of update...
Users.update({email: abc#abc.com}, {'$set': {telephoneNumber : 654321}, function(err, result){
if(err || result.ok === 0){
//err
}else if(result.nModified === 0){
//update fail
}else if(result.n === 0){
//could not be found
}else{
//update success
}
});
Is this a bad approach to update handling in mongoose/mongodb?
Thanks!! :)
Here is how we handle mongoose/mongodb errors. They might be errors like "that value already exists" Or similar issues.
First in the error block of the mongoose call we add:
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err,req,res)
});
}
Which calls a 'getErrorMessage' function which is defined in our errorHandler file, which might call the unique error message function. We also log the errors in our mongo database under a separate collection.
exports.getErrorMessage = function(err,req,res) {
var message = '';
if (err.code) {
switch (err.code) {
case 11000:
case 11001:
message = getUniqueErrorMessage(err);
break;
default:
message = 'Something went wrong. We have logged this issue and will correct';
}
} else {
for (var errName in err.errors) {
if (err.errors[errName].message) message = err.errors[errName].message;
}
}
//log the error to Mongo
ErrorLog.create(err,req,res);
return message;
};
var getUniqueErrorMessage = function(err) {
var output;
try {
var fieldName = err.err.substring(err.err.lastIndexOf('.$') + 2, err.err.lastIndexOf('_1'));
output = fieldName.charAt(0).toUpperCase() + fieldName.slice(1) + ' already exists';
} catch (ex) {
output = 'Unique field already exists';
}
return output;
};
Hope that helps, let me know if I can clarify anything.
async.forEach(vsr.vehicles, function(vsr_vehicle, callback){
pjCustom.vehicleJson(vsr_vehicle, function(vehicleInitialize){
Vehicle.find({ where: { vehicleID: (vsr_vehicle.vehicleID).toString().trim() } }).success(function(vehicleFound){
if(vehicleFound){
//Code Logic is working fine.
}else{
vehicleBuild.save().success(function(vehicleNew){ // To create new vehicle of updated vsr
var vehicleBuild = Vehicle.build(vehicleInitialize)
pj.log("Update vehicle ............................")
temp.push(vehicleNew.vehicleID)
})
}
})
})
callback()
},function(){
res.send(204)
})
//vehicleJSON
exports.vehicleJson = function(vsr_vehicle, callback){
pjCustom.getVehicle(vsr_vehicle, function(status, vehicleId){
if (status == true) {
vsr_vehicle.vehicleID = vehicleId
callback(
{ 'vehicleID':vsr_vehicle.vehicleID).toString().trim(),'vsr_id':vsr_vehicle.vsr_id})
}
})
}
//getvehicle
exports.getVehicle = function(vsr_vehicle, callback){
if(vsr_vehicle.vehicleID !== undefined){
callback(true, vsr_vehicle.vehicleID)
}else{
Vehicle.find({ where: { 'vsr_id': vsr_vehicle.vsr_id },
attributes: ['id', 'vehicleID'],'order': 'id DESC', 'limit': '1'
}).success(function(vehicles){
var temp = (vehicles.vehicleID).split("-")
var newvehicleId = temp[0]+"-"+temp[1]+"-"+(parseInt(temp[2])+1)
callback(true, newvehicleId)
})
}
}
Explanation:
while inserting a record from vsr_vehicle. I need to check whether the vehicleID is present then it will fetch if not it will creates a new Id.
Consider this code is for updating a vehicle as well as inserting another "two" new vehicles. how to manage async process. of insertion of new vehicles.
it is not waiting for completion of first iteration and going for vehicleJson and generating same vehicleID for both new vehicles. suggest me to complete this challange.
My Code is clearly written here.
Please requesting before reading pls copy the code and paste in any JS editor you definitely will understand more than my explanation.
Your callback call in series.forEach is at the incorrect place. Here is the correction:
async.forEach(vsr.vehicles, function(vsr_vehicle, callback){
pjCustom.vehicleJson(vsr_vehicle, function(vehicleInitialize){
Vehicle.find({ where: { vehicleID: (vsr_vehicle.vehicleID).toString().trim() } }).success(function(vehicleFound){
if(vehicleFound){
callback(); // <--- call here
}else{
vehicleBuild.save().success(function(vehicleNew){ // To create new vehicle of updated vsr
var vehicleBuild = Vehicle.build(vehicleInitialize);
pj.log("Update vehicle ............................");
temp.push(vehicleNew.vehicleID);
callback(); // <--- call here
});
}
});
});
// callback(); // <--- Don't call here
},function(){
res.send(204);
});
BTW, for good practice, use semicolon (";") at the end of javascript statements
I am using mongoose with koa.js (maybe a bad choice but had to stick with it).
My initial callback function was :
var _project = yield parse(this);
var userdetails = this.req.user;
var that = this ;
//=============================================================
//FInd a user , check the project name exists under the user, if not then create one
//=============================================================
User.findOne({ '_id': userdetails._id }, function (err, user) {
if (err) {
this.body = "please login again , your session seems to have expired"
} console.log(user.projects.owner.indexOf(_project.name));
if(user.projects.owner.indexOf(_project.name) == -1) { //This means the project is not yet created
var temp_project = new Project(_project);
temp_project.save(function save() {
if(err) {
that.body = "Project coudn't be saved, Please try again sometime later";
} else {
user.projects.owner.push(_project.name);
user.save(function save() {
if (err) {
that.body = "This error is highly unlikely, yet if you see this .Please report this issue";
}
});
that.body = temp_project;
}
});
}
if(user.projects.owner.indexOf(_project.name) >= 0) { //THis means the project exists
that.body = "You have already created a project with same name, please use a different name";
console.log("you reached till here");
}
});
This should have worked in normal express world but later I realised that I need to rewrite in the forms of thunks so my current attemp is
function userfindONE(err, user) {
if (err) {
return "please login again , your session seems to have expired"
}
if(user.projects.owner.indexOf(tproject.name) == -1) { //This means the project is not yet created
var temp_project = new Project(tproject);
temp_project.save(function save() {
if(err) {
return "Project coudn't be saved, Please try again sometime later";
} else {
user.projects.owner.push(tproject.name);
user.save(function save() {
if (err) {
return "This error is highly unlikely, yet if you see this .Please report this issue";
}
});
return temp_project;
}
});
}
if(user.projects.owner.indexOf(tproject.name) >= 0) { //THis means the project exists
return "You have already created a project with same name, please use a different name";
} else return "nothing is matching";
}
function userfindone(userdetails) {
return function(cb) {
User.findOne({ '_id': userdetails._id }, cb);
};
}
var userdetails = this.req.user;
var tproject = yield parse(this);
But this returns the user details from the User.findone from the first mongoose call.
and anything else seems to have ignored. Thanks
this.body = yield userfindone(userdetails)(userfindONE) ;
Take a look at node-thunkify. It should be as simple as wrapping your schema's functions with it.
With Mongoose 3.9.x you can simply yield user.save(), check in your package.json you have installed the unstable release.
I'm new to Node and CouchDb and I'm trying to get my hands on it.
I'm struggling to make a piece of code to work.
I would like to create a table users, insert a new user and 'at the same time' getting another user.
I'm getting this error when starting up node app.js :
antoine#ubuntu:~/projects/couchDb$ node app.js
Database users exists.
{"error":"conflict","reason":"Document update conflict."}
Leaving saveDoc
events.js:48
throw arguments[1]; // Unhandled 'error' event
^
Error: socket hang up
at createHangUpError (http.js:1107:15)
at Socket.onend (http.js:1188:27)
at TCP.onread (net.js:369:26)
And here is my very code, is there something wrong?
(When I remove the getDoc function the error goes away)
I'm using couchDB 1.0.1 and node 0.6.12
The jdoe4 and jdoe documents are already present in the users database.
var dbHost = "127.0.0.1";
var dbPort = 5984;
var dbName = 'users';
var couchdb = require('felix-couchdb');
var client = couchdb.createClient(dbPort, dbHost);
var user = {
name: {
first: 'John',
last: 'Doe'
}
}
var db = client.db(dbName);
db.exists(function(err, exists) {
if (!exists) {
db.create();
console.log('Database ' + dbName + ' created.');
} else {
console.log('Database ' + dbName + ' exists.');
}
db.saveDoc('jdoe4', user, function(err, doc) {
if( err) {
console.log(JSON.stringify(err));
} else {
console.log('Saved user.');
}
console.log('Leaving saveDoc');
});
db.getDoc('jdoe', function(err,doc) {
if( err) {
console.log(JSON.stringify(err));
} else {
console.log(JSON.stringify(doc));
}
console.log('Leaving getDoc');
});
});
It seems to be a library problem => Github Issue Socket Hangout
Look here if you dont know which library fit more your needs.
I quickly realized that felix-couchdb is not compatible with node 8 (I know you're not using version 8, but you will someday), so I switched to nano couchdb and here's the following code:
It will check if the db is created
It will insert only if the key given is unique
It will get the user with a key
var couchdb = require('nano')('http://localhost:5984')
, dbName = 'users'
, db = couchdb.use(dbName)
;
var user = {
name: {
first: 'John',
last: 'Doe'
}
}
couchdb.db.create(dbName, function(err, db_body) {
db.insert(user, 'jdoe4', function(err, doc, header) {
if( err) {
console.log('Cannot save user');
} else {
console.log('Saved user.');
}
console.log('Leaving saveDoc');
});
db.get('jdoe', function(err, doc) {
if( err) {
console.log('Cannot get user');
} else {
console.log(JSON.stringify(doc));
}
console.log('Leaving getDoc');
});
});
One thing worth noting is that, while this will get them at the "same time," it's still making 3 requests to the db, 1 to check if it exists, 1 to insert (or not), 1 to get.