I have AWS redis which stores some data. I want to get the stored data using the Redis endpoint URL and nodejs. Below are my code and response which I am getting.
code:
let client = require('redis').createClient('redis://abcbsamv:6379', {no_ready_check: true});
res.send(client)
response from the above code:
{
"_events": {},
"_eventsCount": 1,
"address": "endpoints:6379",
"connection_options": {
"port": 6379,
"host": "endpoints",
"family": 4
},
"connection_id": 0,
"connected": false,
"ready": false,
"should_buffer": false,
"max_attempts": 0,
"command_queue": [],
"offline_queue": [],
"pipeline_queue": [],
"connect_timeout": 3600000,
"enable_offline_queue": true,
"retry_max_delay": null,
"retry_timer": null,
"retry_totaltime": 0,
"retry_delay": 200,
"retry_backoff": 1.7,
"attempts": 1,
"pub_sub_mode": 0,
"subscription_set": {},
"monitoring": false,
"message_buffers": false,
"closing": false,
"server_info": {},
"old_state": null,
"fire_strings": true,
"pipeline": false,
"sub_commands_left": 0,
"times_connected": 0,
"buffers": false,
"options": {
"port": "6379"
}
Please help me.
Related
I have a code like this
let item = { name: 'Roger' }
try {
return await collection.save(item)
}
catch (err) {
}
Now the collection I'm saving to has a Unique index on the field called name. Now during the exception handling the err object would look something like this
{
"isArangoError": true,
"response": {
"_readableState": {
"objectMode": false,
"highWaterMark": 16384,
"buffer": {
"head": null,
"tail": null,
"length": 0
},
"length": 0,
"pipes": [
],
"flowing": true,
"ended": true,
"endEmitted": true,
"reading": false,
"sync": true,
"needReadable": false,
"emittedReadable": false,
"readableListening": false,
"resumeScheduled": false,
"paused": false,
"errorEmitted": false,
"emitClose": true,
"autoDestroy": false,
"destroyed": false,
"defaultEncoding": "utf8",
"awaitDrainWriters": null,
"multiAwaitDrain": false,
"readingMore": true,
"decoder": null,
"encoding": null
},
"body": {
"code": 409,
"error": true,
"errorMessage": "unique constraint violated - in index name_is_unique of type persistent over 'name'; conflicting key: 15816187",
"errorNum": 1210
},
"arangojsHostId": 0
},
"statusCode": 409,
"errorNum": 1210,
"code": 409
}
While the error message is indeed helpful in conveying that name should be unique, wish there is an attribute/field in the error object to grab the conflicted field name.
How to get the field name other than regex parsing from the error message?
I'm trying to map a local directory to a folder on my hosting provider, but I get a connection timeout error.
I've tried logging on from different ISP's, but I still get the same error. And I use these same credentials successfully in Filezilla.
Here is my config file:
{
// sftp, ftp or ftps
"type": "sftp",
"save_before_upload": true,
"upload_on_save": false,
"sync_down_on_open": false,
"sync_skip_deletes": false,
"sync_same_age": true,
"confirm_downloads": false,
"confirm_sync": true,
"confirm_overwrite_newer": false,
"host": "mydomain.com",
"user": "myusername",
"password": "mypassword",
// "port": "22",
"remote_path": "/",
"ignore_regexes": [
"\\.sublime-(project|workspace)", "sftp-config(-alt\\d?)?\\.json",
"sftp-settings\\.json", "/venv/", "\\.svn/", "\\.hg/", "\\.git/",
"\\.bzr", "_darcs", "CVS", "\\.DS_Store", "Thumbs\\.db", "desktop\\.ini"
],
//"file_permissions": "664",
//"dir_permissions": "775",
//"extra_list_connections": 0,
"connect_timeout": 30,
//"keepalive": 120,
//"ftp_passive_mode": true,
//"ftp_obey_passive_host": false,
//"ssh_key_file": "~/.ssh/id_rsa",
//"sftp_flags": ["-F", "/path/to/ssh_config"],
//"preserve_modification_times": false,
//"remote_time_offset_in_hours": 0,
//"remote_encoding": "utf-8",
//"remote_locale": "C",
//"allow_config_upload": false,
}
I've been trying to add emails (which is a new field) to my "people" collection but I don't know why I'm getting no results from the server. This is my code
for (key in D_emails) {
console.log(D_emails[key])
try {
o_id = new mongo.ObjectID(D_emails[key])
collection.updateOne({
_id: o_id
}, {
$set: {
"Email": key
}
}, function(err, results) {
if (err) {
throw err
} else if (results.length) {
console.log(results)
} else {
console.log("no results")
}
});
} catch (e) {
print(e);
}
}
According to mongo documentation for updateOne the response of the query (results in your case) does not contain length element and it is not an array or an object. This will be the response according to the documentation:
Returns a document containing:
A boolean acknowledged as true if the operation ran with write concern or false if write concern was disabled
matchedCount containing the number of matched documents
modifiedCount the number of modified documents upsertedId containing the _id for
the upserted document
first of all. try to code without try catch blocks when using the concept of "err" object being returned from every asynchronous callback. You can treat the error right inside the callback. "throwing" the error will also prevent other emails from being updated. But maybe that's what you want. It doesn't really matter now.
Now, back to your question. let me show you what result is, in this example:
// inserting.
collection.insertOne({_id: "lala", a:10, b:20}, function (err, r) {
assert.equal(null, err);
assert.equal(1, r.insertedCount);
// updating.
collection.updateOne({_id: "lala"}, {$set: {a: 99}}, {}, function(err, result) {
assert.equal(null, err);
console.log(result) // first thing printed.
console.log(JSON.stringify(result, null, "\t")) // second print.
// checking whats inside it.
collection.findOne({_id: "lala"}, {}, function(err, doc) {
assert.equal(null, err);
console.log(doc) // third print.
db.close() // don't close connection if you don't need to.
})
})
})
the 3 printed things will be (scroll to the end to see what you actually want):
CommandResult {
result: { ok: 1, nModified: 1, n: 1 },
connection:
Connection {
domain: null,
_events:
{ close: [Object],
error: [Object],
timeout: [Object],
parseError: [Object],
connect: [Function] },
_eventsCount: 5,
_maxListeners: undefined,
options:
{ socketOptions: {},
auto_reconnect: true,
host: 'localhost',
port: 27017,
cursorFactory: [Object],
reconnect: true,
emitError: true,
size: 5,
disconnectHandler: [Object],
bson: BSON {},
messageHandler: [Function],
wireProtocolHandler: [Object] },
id: 1,
logger: Logger { className: 'Connection' },
bson: BSON {},
tag: undefined,
messageHandler: [Function],
maxBsonMessageSize: 67108864,
port: 27017,
host: 'localhost',
keepAlive: true,
keepAliveInitialDelay: 0,
noDelay: true,
connectionTimeout: 0,
socketTimeout: 0,
destroyed: false,
domainSocket: false,
singleBufferSerializtion: true,
serializationFunction: 'toBinUnified',
ca: null,
cert: null,
key: null,
passphrase: null,
ssl: false,
rejectUnauthorized: false,
checkServerIdentity: true,
responseOptions: { promoteLongs: true },
flushing: false,
queue: [],
connection:
Socket {
connecting: false,
_hadError: false,
_handle: [Object],
_parent: null,
_host: 'localhost',
_readableState: [Object],
readable: true,
domain: null,
_events: [Object],
_eventsCount: 8,
_maxListeners: undefined,
_writableState: [Object],
writable: true,
allowHalfOpen: false,
destroyed: false,
_bytesDispatched: 334,
_sockname: null,
_pendingData: null,
_pendingEncoding: '',
server: null,
_server: null,
_idleNext: null,
_idlePrev: null,
_idleTimeout: -1,
read: [Function],
_consuming: true },
writeStream: null,
hashedName: '29bafad3b32b11dc7ce934204952515ea5984b3c',
buffer: null,
sizeOfMessage: 0,
bytesRead: 0,
stubBuffer: null },
matchedCount: 1,
modifiedCount: 1,
upsertedId: null,
upsertedCount: 0 }
{
"ok": 1,
"nModified": 1,
"n": 1
}
{ _id: 'lala', a: 99, b: 20 }
the first object is the result returned from "updateOne()".
the second object is the result's "toString()" implementation and this is what's inside result.result (scroll back to top).
the last object is what I get after querying for the updated document.
you can find more examples on the native mongodb driver for nodejs website: http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#updateOne
their are full of examples.
After following the advice presented here:
(OpenShift) Sharing MongoDB between Apps not possible anymore?
...which in a nutshell is this -> "You need to create the application as scalable, then add MongoDB for it to work correctly. MongoDB will then go onto it's own gear, with it's own ip address and port number (remember to use this port number, or nothing will work)."
...I am still unable to successfully connect my Node.js app to the MongoDB database living on another Node.js app in Openshift.
I have tried the following permutations of a host string that have been suggested:
localhost
128.xxx.xxx.xxx
[24 character hash]-myapp-mydomain.rhcloud.com
...all with the same result. No connection.
Here is the code that makes the call to setup the db connection...
dbProvider = function(host, port, user, pass) {
console.re.log("Attempting to create a DB instance...");
this.db = new Db(process.env.OPENSHIFT_MONGODB_EXTDB_DBNAME, new Server(host, port, { auto_reconnect: true }, {}));
console.re.log("created the DB instance...");
if(this.db!= null){
console.re.log("successfully connected to remote db %s at %s:%s",this.db,host,port);
this.db.open(function(error, db){
if(error){
console.re.log("error %s attempting to open the db at %s:%s",error,host,port);
}
else{
db.authenticate(user, pass, function(error, result) { //db.authenticate(user, pass, function(error, result)
if(error){
console.re.log("error %s attempting to connect to remote db at %s:%s using user %s",error,host,port,user);
}
else{
console.re.log("successfully connected to remote db at %s:%s using user %s",host,port,user);
}
});
}
});
}
else{
console.re.log("unable to connect to remote db at %s:%s",host,port);
}
}
The above code fails at the callback from the db.open() with a null error object.
Upon inspecting the this.db object we see the following:
{
"domain": null,
"_events": {},
"_maxListeners": 10,
"databaseName": "myDb",
"serverConfig": {
"domain": null,
"_events": {},
"_maxListeners": 10,
"host": "xxxxxxxxxxxxxxxxxxxxxxxx-myApp-myDomain.rhcloud.com",
"port": 12345,
"options": {
"auto_reconnect": true
},
"internalMaster": false,
"connected": false,
"poolSize": 5,
"disableDriverBSONSizeCheck": false,
"ssl": false,
"_used": true,
"_readPreference": null,
"socketOptions": {},
"logger": {
"error": "[Function]",
"log": "[Function]",
"debug": "[Function]"
},
"eventHandlers": {
"error": [],
"parseError": [],
"poolReady": [],
"message": [],
"close": [],
"timeout": []
},
"_serverState": "disconnected",
"_state": {
"runtimeStats": {
"queryStats": {
"m_n": 0,
"m_oldM": 0,
"m_oldS": 0,
"m_newM": 0,
"m_newS": 0,
"numDataValues": 0,
"mean": 0,
"variance": 0,
"standardDeviation": 0,
"sScore": 0
}
}
},
"recordQueryStats": false
},
"options": {},
"_applicationClosed": false,
"bsonLib": {
"Code": "[Function]",
"Symbol": "[Function]",
"BSON": "[Function]",
"DBRef": "[Function]",
"Binary": "[Function]",
"ObjectID": "[Function]",
"Long": "[Function]",
"Timestamp": "[Function]",
"Double": "[Function]",
"MinKey": "[Function]",
"MaxKey": "[Function]"
},
"bson": {},
"bson_deserializer": "[ Circular {bsonLib} ]",
"bson_serializer": "[ Circular {bsonLib} ]",
"_state": "disconnected",
"pkFactory": "[Function]",
"forceServerObjectId": false,
"safe": false,
"notReplied": {},
"isInitializing": true,
"auths": [],
"openCalled": false,
"commands": [],
"_callBackStore": {
"domain": null,
"_events": {},
"_maxListeners": 10,
"_notReplied": {}
},
"logger": "[ Circular {logger} ]",
"slaveOk": false,
"tag": 1460656848883,
"eventHandlers": {
"error": [],
"parseError": [],
"poolReady": [],
"message": [],
"close": []
},
"serializeFunctions": false,
"raw": false,
"recordQueryStats": false,
"reaperEnabled": false,
"_lastReaperTimestamp": 1460656848883,
"retryMiliSeconds": 1000,
"numberOfRetries": 60,
"reaperInterval": 10000,
"reaperTimeout": 30000
}
Note: The host, port, and databaseName fields have been modified for privacy.
This db object differs from a properly connecting db object by only two fields...
...both db.serverConfig._serverState and db._state equal 'connected' vs. 'disconnected'
Appreciate hearing from anyone that has successfully accomplished what I am trying to do.
Thanks!
i want to make a request to a page using request module in node js, but this have a error 500 .
This is part of the json response
{
"readable": false,
"domain": null,
"_maxListeners": 10,
"httpVersion": "1.1",
"complete": true,
"_pendingIndex": 0,
"url": "",
"method": null,
"statusCode": 500,
"_consuming": true,
"_dumped": false,
"httpVersionMajor": 1,
"httpVersionMinor": 1,
"upgrade": false,
"body": "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\n<html><head>\n<title>500 Not Found</title>\n</head><body>\n<h1>Not Found</h1>\n<p>The requested\n site HTTP/1.1 is not presently available on\n this web cluster.\n This may be a temporary issue, so please try again in a few\n moments.</p>\n\n</body></html>\n",
"_readableState": {
"highWaterMark": 16384,
"length": 0,
"pipes": null,
"pipesCount": 0,
"flowing": false,
"ended": true,
"endEmitted": true,
"reading": false,
"calledRead": true,
"sync": false,
"needReadable": true,
"emittedReadable": false,
"readableListening": false,
"objectMode": false,
"defaultEncoding": "utf8",
"ranOut": false,
"awaitDrain": 0,
"readingMore": false,
"decoder": null,
"encoding": null,
"buffer": []
},
This is the code that i use for the request
app.get('/', function(req, res){
var options = {
url: 'http://www.metallicabyrequest.com/'
}
request(options, function (error, response, html) {
/*if (!error && response.statusCode == 200) {
res.json(html);
}*/
if(error){
res.json(error);
}else{
res.json(response)
}
});
});
Is there any way to get prevent the error 500? I read that if you change the headers, is probably that the request works, but i don't know how to do ...
That site require 'Host' in request header:
var options = {
url: 'http://www.metallicabyrequest.com/',
headers: {
'Host': 'www.metallicabyrequest.com'
}
}