I have a Problem with the orientjs Driver (https://github.com/orientechnologies/orientjs) or my OrientDB (v2.1.15). I have a Node.js Server and open a Connection to the Database Server like this:
var OrientDB = require('orientjs');
var orientserver = OrientDB({
host: 'localhost',
port: 2424,
username: 'root',
password: 'Orientdb'
});
Next I open a Database Connection and work with this DB, all works fine to this point. But if I want to list all Databases with the orientserver.list() Method I get this Error:
Unhandled rejection OrientDB.RequestError: Server user not authenticated.
at Operation.parseError (/home/mklaus/IdeaProjects/Thesis/node_modules/orientjs/lib/transport/binary/protocol28/operation.js:855:13)
at Operation.consume (/home/mklaus/IdeaProjects/Thesis/node_modules/orientjs/lib/transport/binary/protocol28/operation.js:446:35)
at Connection.process (/home/mklaus/IdeaProjects/Thesis/node_modules/orientjs/lib/transport/binary/connection.js:383:17)
at Connection.handleSocketData (/home/mklaus/IdeaProjects/Thesis/node_modules/orientjs/lib/transport/binary/connection.js:284:17)
at emitOne (events.js:90:13)
at Socket.emit (events.js:182:7)
at readableAddChunk (_stream_readable.js:147:16)
at Socket.Readable.push (_stream_readable.js:111:10)
at TCP.onread (net.js:525:20)
To find the Issue I logged my Server at this Moment and get:
Server {
useToken: false,
logger:
{ error: [Function: bound bound ],
log: [Function: bound bound ],
debug: [Function] },
transport:
BinaryTransport {
domain: null,
_events: { reset: [Function: bound ] },
_eventsCount: 1,
_maxListeners: Infinity,
connecting:
Promise {
_bitField: 268566529,
_fulfillmentHandler0: undefined,
_rejectionHandler0: undefined,
_progressHandler0: undefined,
_promise0: undefined,
_receiver0: undefined,
_settledValue: [Circular],
_boundTo: [Circular] },
closing: false,
retries: 0,
maxRetries: 5,
host: 'localhost',
port: 2424,
username: 'admin',
password: 'admin',
servers: [ [Object] ],
currentServer: 0,
enableRIDBags: true,
useToken: false,
token: <Buffer >,
sessionId: 62,
logger:
{ error: [Function: bound bound ],
log: [Function: bound bound ],
debug: [Function] },
connection:
Connection {
domain: null,
_events: [Object],
_eventsCount: 3,
_maxListeners: Infinity,
host: 'localhost',
port: 2424,
socket: [Object],
logger: [Object],
enableRIDBags: true,
closing: false,
reconnectNow: false,
protocol: [Object],
queue: [],
writes: [],
remaining: null,
connecting: false,
protocolVersion: 32 },
skipServerConnect: true },
config:
{ get: [Function: bound ],
set: [Function: bound ],
list: [Function: bound ] },
domain: null,
_events:
{ reset:
[ [Function: bound ],
[Function: bound ],
[Function: bound ],
[Function: bound ],
[Function: bound ] ],
error: [ [Object], [Object] ] },
_eventsCount: 2,
_maxListeners: Infinity }
As you can see the username and the Password is wrong. Someone know why this happen? Why I cant have Access to the Server after working with one DB on it?
*edit
Here is the Code of my nodejs Server (Not everything, just the important parts)
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var stringify = require('json-stringify-safe');
var routes = require('./routes/index');
var users = require('./routes/users');
var passport = require('passport');
var expressSession = require('express-session');
var Strategy = require('passport-local').Strategy;
var users = {};
var databases = {};
var OrientDB = require('orientjs');
var orientserver = OrientDB({
host: 'localhost',
port: 2424,
httpPort: 2480,
username: 'root',
password: 'Orientdb'
});
passport.use(new Strategy({
usernameField: 'username',
passwordField: 'password',
passReqToCallback: true
},
function(req, username, password, cb) {
var sessID = req.sessionID;
var dbkey = username+"_"+req.params.database;
if(dbkey in databases) {
} else {
databases[dbkey] = orientserver.use({
name: req.params.database,
username: username,
password: password
});
}
users[sessID]= {id: sessID, username: username, database: dbkey};
return cb(null, users[sessID]);
}));
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(expressSession({secret: 'mySecretKey', cookie: { maxAge: 60000 }}));
app.use(passport.initialize());
app.use(passport.session());
app.get('/', function (req, res) {
});
app.get('/getAllProjects', function(req, res) {
//https://github.com/kriskowal/q
orientserver.list()
.then(function (dbs) {
var json = [];
dbs.forEach(function(value, index) {
json.push({"name": value.name});
});
//console.log('There are ' + dbs.length + ' databases on the server.');
res.status(200).send(json);
});
});
app.post('/:database',
passport.authenticate('local', { failureRedirect: '/' }),
function(req, res) {
res.redirect("/"+req.params.database);
});
So when I send the second Request to getAllProjects I get the Error.
Related
I have a datamodel named 'account' that stores a 'user'
var mongoose=require("mongoose");
mongoose.connect("mongodb://localhost/dataseed");
var db=mongoose.connection;
var accountSchema=mongoose.Schema({
user:{
type:mongoose.Schema.Types.ObjectId,
ref:"user"
},
accountholder:{
type:String
},
cvv:{
type:String
},
expiryyear:{
type:String
},
expirymonth:{
type:String
},
accountnumber:{
type:Number
},
currentamount:{
type:Number
},
transferedamount:{
type:Number
},
withdrawnamount:{
type:Number
}
});
var account = module.exports = mongoose.model('account', accountSchema);
When I'm trying to found an account using the account.find() function. However it returns undefined when I try to access account.accountnumber
I'm querying my model as follows:
data.findById({"_id":req.params.id},function(err,data){
console.log("DATA.USER --------------------------------------------------");
console.log(data.user);
if(err)console.log(err);
else{
acessToken.create({user:req.user,data:req.params.id,token:token},function(err,acess){
if(err)console.log(err);
else{
console.log("ACCESSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSss");
console.log(acess.user);
transporter.sendMail(mailOptions, function(error, info){
if (error) {
console.log(error);
}
else
{
console.log("------------------------------------------------------------------------------------TYPE OF USER ID: " + typeof(req.user._id));
account.find({"user":req.user},function(err,d){
if(err)console.log(err)
var amount=d.currentamount-data.price;
var transferedamount=d.transferedamount+data.price;
console.log("Amount: "+amount); // NaN
account.findByIdAndUpdate({user:req.user},{currentamount:amount,transferedamount:transferedamount},function(err,update){
if(err)console.log(err);
console.log('Email sent: ' + info.response);
//getUsername of seller
// console.log(data.user)
user.findById({"_id":data.user},function(err,seller){
if(err){
console.log(err);
}else{
var buyer = req.user.username;
var seller = seller.username;
var priceOfData = data.price;
//ccNumber undefined
var ccnumber = d.accountnumber;
console.log("Buyer Name " +buyer);
console.log("Seller Name " +seller);
console.log("Price " +priceOfData);
console.log("Purchased on Credit Card Number " +ccnumber);
res.render('buyer/sold.ejs');
}
});
});
});
}
});
}
});
}
});
Models "data" and "acessToken" are used for finding a product and generating an access token of the purchased product.
This is the output im getting on my console.
5ca9ae4c044bab18588edf5b
ACCESSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSss
5cd4cc83c3c65514c61ae4f3
------------------------------------------------------------------------------------TYPE OF USER ID: object
Amount: NaN
{ CastError: Cast to ObjectId failed for value "{ user: 5cd4cc83c3c65514c61ae4f3 }" at path "_id" for model "account"
at MongooseError.CastError (/home/ubuntu/workspace/DataSeed/node_modules/mongoose/lib/error/cast.js:29:11)
at ObjectId.cast (/home/ubuntu/workspace/DataSeed/node_modules/mongoose/lib/schema/objectid.js:232:11)
at ObjectId.SchemaType.applySetters (/home/ubuntu/workspace/DataSeed/node_modules/mongoose/lib/schematype.js:845:12)
at ObjectId.SchemaType._castForQuery (/home/ubuntu/workspace/DataSeed/node_modules/mongoose/lib/schematype.js:1248:15)
at ObjectId.SchemaType.castForQuery (/home/ubuntu/workspace/DataSeed/node_modules/mongoose/lib/schematype.js:1238:15)
at ObjectId.SchemaType.castForQueryWrapper (/home/ubuntu/workspace/DataSeed/node_modules/mongoose/lib/schematype.js:1217:15)
at cast (/home/ubuntu/workspace/DataSeed/node_modules/mongoose/lib/cast.js:252:34)
at Query.cast (/home/ubuntu/workspace/DataSeed/node_modules/mongoose/lib/query.js:4334:12)
at castQuery (/home/ubuntu/workspace/DataSeed/node_modules/mongoose/lib/query.js:4186:18)
at Query._findAndModify (/home/ubuntu/workspace/DataSeed/node_modules/mongoose/lib/query.js:3203:23)
at Query.<anonymous> (/home/ubuntu/workspace/DataSeed/node_modules/mongoose/lib/query.js:2830:8)
at Query._wrappedThunk [as _findOneAndUpdate] (/home/ubuntu/workspace/DataSeed/node_modules/mongoose/lib/helpers/query/wrapThunk.js:16:8)
at process.nextTick (/home/ubuntu/workspace/DataSeed/node_modules/kareem/index.js:369:33)
at _combinedTickCallback (internal/process/next_tick.js:73:7)
at process._tickCallback (internal/process/next_tick.js:104:9)
message: 'Cast to ObjectId failed for value "{ user: 5cd4cc83c3c65514c61ae4f3 }" at path "_id" for model "account"',
name: 'CastError',
stringValue: '"{ user: 5cd4cc83c3c65514c61ae4f3 }"',
kind: 'ObjectId',
value: { user: 5cd4cc83c3c65514c61ae4f3 },
path: '_id',
reason: undefined,
model:
{ [Function: model]
hooks: Kareem { _pres: [Object], _posts: [Object] },
base:
Mongoose {
connections: [Object],
models: [Object],
modelSchemas: [Object],
options: [Object],
_pluralize: [Function: pluralize],
Schema: [Object],
model: [Function],
plugins: [Object] },
modelName: 'account',
model: [Function: model],
db:
NativeConnection {
base: [Object],
collections: [Object],
models: [Object],
config: [Object],
replica: false,
options: null,
otherDbs: [],
relatedDbs: {},
states: [Object],
_readyState: 1,
_closeCalled: false,
_hasOpened: true,
'$internalEmitter': [Object],
_listening: false,
_events: [Object],
_eventsCount: 1,
_connectionOptions: [Object],
name: 'dataseed',
host: 'localhost',
port: 27017,
user: undefined,
pass: undefined,
client: [Object],
'$initialConnection': [Object],
db: [Object] },
discriminators: undefined,
events:
EventEmitter {
domain: null,
_events: {},
_eventsCount: 0,
_maxListeners: undefined },
'$appliedMethods': true,
'$appliedHooks': true,
_middleware: Kareem { _pres: [Object], _posts: [Object] },
schema:
Schema {
obj: [Object],
paths: [Object],
aliases: {},
subpaths: {},
virtuals: [Object],
singleNestedPaths: {},
nested: {},
inherits: {},
callQueue: [],
_indexes: [],
methods: {},
methodOptions: {},
statics: {},
tree: [Object],
query: {},
childSchemas: [],
plugins: [Object],
'$id': 7,
s: [Object],
_userProvidedOptions: {},
options: [Object],
'$globalPluginsApplied': true,
_requiredpaths: [] },
collection:
NativeCollection {
collection: [Object],
opts: [Object],
name: 'accounts',
collectionName: 'accounts',
conn: [Object],
queue: [],
buffer: false,
emitter: [Object] },
Query: { [Function] base: [Object] },
'$__insertMany': [Function],
'$init': Promise { [Object] },
'$caught': true } }
Email sent: 250 2.0.0 OK 1557500841 d4sm5108746wrv.42 - gsmtp
Buyer Name murtaza1
Seller Name test1
Price 100
Purchased on Credit Card Number undefined
The problem with your code is that when you query your database you also need to call the populate method exposed by MongoDB and in particular Mongoose which I'm assuming you're using to query the DB. More info on Mongoose docs.
Why this happens? Well, since you're declaring using as a reference to your account Schema when Mongoose query the DB it only returns, without the populate method, the ID of the document referenced by that particular account Schema. Hope this helps you, cheers, sigfried
I have tried making the same post request using node-fetch and axios.
var fetch = require('node-fetch');
var axios = require('axios');
async function fetchTest(host, port, body) {
const response = {
successMessage: '',
errorMessage: ''
}
try {
const streamResponse = await fetch(`${host}:${port}`, {
method: 'post',
body: JSON.stringify(body)
})
const jsonResponse = await streamResponse.json()
response.successMessage = jsonResponse;
} catch (error) {
response.errorMessage = error;
}
return response;
}
async function axiosTest(host, port, body) {
const response = {
successMessage: '',
errorMessage: ''
}
try {
const jsonResponse = await axios({
method: 'post',
url: `${host}:${port}`,
data: body
})
response.successMessage = jsonResponse;
} catch (error) {
response.errorMessage = error;
}
return response;
}
async function test() {
console.log(await fetchTest('http://127.0.0.1', '8801', { type: 'request', cmd: 'devices' }));
console.log(await axiosTest('http://127.0.0.1', '8801', { type: 'request', cmd: 'devices' }));
}
test();
The request made with node-fetch works nicely. The request made with axios returns (IP address redacted with ...) an error:
{ successMessage: '',
errorMessage:
{ Error: connect ECONNREFUSED ...:80
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1161:14)
errno: 'ECONNREFUSED',
code: 'ECONNREFUSED',
syscall: 'connect',
address: '...',
port: 80,
config:
{ adapter: [Function: httpAdapter],
transformRequest: [Object],
transformResponse: [Object],
timeout: 0,
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN',
maxContentLength: -1,
validateStatus: [Function: validateStatus],
headers: [Object],
method: 'post',
url: 'http://127.0.0.1:8801',
data: '{"type":"request","cmd":"devices"}' },
request:
Writable {
_writableState: [WritableState],
writable: true,
_events: [Object],
_eventsCount: 2,
_maxListeners: undefined,
_options: [Object],
_redirectCount: 1,
_redirects: [],
_requestBodyLength: 39,
_requestBodyBuffers: [],
_onNativeResponse: [Function],
_currentRequest: [ClientRequest],
_currentUrl: 'http://.../',
_isRedirect: true },
response: undefined } }
What might be the reason? Am I doing something wrong?
EDITED with more info requested in comment:
The axios request fails the same way if I comment out the node-fetch request.
The node-fetch request returns:
{
cmd: 'devices',
payload: { devices: [Array] },
type: 'response' },
}
Since I wrap the result in a response object, the console.log looks like
{
successMessage:
{
cmd: 'devices',
payload: { devices: [Array] },
type: 'response'
},
errorMessage: ''
}
I used mongo-nodejs 2.2 and upgraded to 3.0. After upgrading, I found that the method db() in Db class doesn't exist anymore (http://mongodb.github.io/node-mongodb-native/3.0/api/Db.html). This method is very useful to switch to different database instance. I wonder how I can switch to different database with the latest version.
Okay so it is gone, and it's documented as gone and the real message is you should be using Mongoclient.prototype.db instead:
From the 3.0 Changes:
We removed the following API methods.
Db.prototype.authenticate
Db.prototype.logout
Db.prototype.open
Db.prototype.db
...
We've added the following API methods.
MongoClient.prototype.logout
MongoClient.prototype.isConnected
MongoClient.prototype.db
The basic lesson here was wherever you were using Db directly, you should be using the MongoClient instance instead. This is obtained from the very first connection:
const { MongoClient } = require('mongodb');
(async function() {
try {
const conn = await MongoClient.connect('mongodb://localhost');
let test = conn.db('test');
let admin = test.admin();
console.log(admin);
let another = conn.db('another');
console.log(another);
} catch(e) {
console.error(e);
} finally {
process.exit();
}
})()
Returns output like:
Admin {
s:
{ db:
Db {
domain: null,
_events: {},
_eventsCount: 0,
_maxListeners: undefined,
s: [Object],
serverConfig: [Getter],
bufferMaxEntries: [Getter],
databaseName: [Getter] },
topology:
Server {
domain: null,
_events: [Object],
_eventsCount: 25,
_maxListeners: Infinity,
clientInfo: [Object],
s: [Object] },
promiseLibrary: [Function: Promise] } }
Db {
domain: null,
_events: {},
_eventsCount: 0,
_maxListeners: undefined,
s:
{ databaseName: 'another',
dbCache: {},
children: [],
topology:
Server {
domain: null,
_events: [Object],
_eventsCount: 25,
_maxListeners: Infinity,
clientInfo: [Object],
s: [Object] },
options:
{ readPreference: [Object],
promiseLibrary: [Function: Promise] },
logger: Logger { className: 'Db' },
bson: BSON {},
readPreference: ReadPreference { mode: 'primary', tags: undefined, options: undefined },
bufferMaxEntries: -1,
parentDb: null,
pkFactory: undefined,
nativeParser: undefined,
promiseLibrary: [Function: Promise],
noListener: false,
readConcern: undefined },
serverConfig: [Getter],
bufferMaxEntries: [Getter],
databaseName: [Getter] }
Interestingly the admin() helper still exists on Db instances, which of course is really just a "pre filled" selection to the old db() anyway.
Bottom line, use the MongoClient instance from the connection instead for all future code.
I am learning mongodb and following a tutorial with the below code:
My index.js file:
var MongoClient = require('mongodb').MongoClient;
var url = 'mongodb://u****:p****#ds131687.mlab.com:31687/learning_mongo';
var findDocuments = function(db, callback) {
var collection = db.collection('tours');
collection.find().toArray(function(err,docs){
if (err) throw err;
console.log(docs);
callback;
})
}
MongoClient.connect(url, function(err, db){
if (err) throw err;
// console.log("it is working");
// db.close();
findDocuments(db, function(){
db.close();
});
})
Unfortunately, I get the following error in terminal:
dosstx:~/workspace $ node index.js
/home/ubuntu/workspace/node_modules/mongodb/lib/mongo_client.js:810
throw err;
^
TypeError: db.collection is not a function
at findDocuments (/home/ubuntu/workspace/index.js:6:25)
at /home/ubuntu/workspace/index.js:20:5
at args.push (/home/ubuntu/workspace/node_modules/mongodb/lib/utils.js:404:72)
at /home/ubuntu/workspace/node_modules/mongodb/lib/mongo_client.js:255:5
at connectCallback (/home/ubuntu/workspace/node_modules/mongodb/lib/mongo_client.js:933:5)
at /home/ubuntu/workspace/node_modules/mongodb/lib/mongo_client.js:807:13
at _combinedTickCallback (internal/process/next_tick.js:73:7)
at process._tickCallback (internal/process/next_tick.js:104:9)
Does anyone have any advice on how to proceed and/or what is causing the error? The tutorial author does not get this error and I can't see what else is different for me (other than possible different versions of MongoDB vs the author's?)
console.log(db) shows:
MongoClient {
domain: null,
_events: {},
_eventsCount: 0,
_maxListeners: undefined,
s:
{ url: 'mongodb://****:****#ds131687.mlab.com:31687/learning_mongo',
options:
{ user: *****,
password: ****,
socketOptions: {},
read_preference_tags: null,
readPreference: [Object],
dbName: 'learning_mongo',
servers: [Object],
auth: [Object],
server_options: [Object],
db_options: [Object],
rs_options: [Object],
mongos_options: [Object],
socketTimeoutMS: 360000,
connectTimeoutMS: 30000,
promiseLibrary: [Function: Promise] },
promiseLibrary: [Function: Promise],
dbCache: {},
sessions: [] },
topology:
Server {
domain: null,
_events:
{ serverOpening: [Function],
serverDescriptionChanged: [Function],
serverHeartbeatStarted: [Function],
serverHeartbeatSucceeded: [Function],
serverHeartbeatFailed: [Function],
serverClosed: [Function],
topologyOpening: [Function],
topologyClosed: [Function],
topologyDescriptionChanged: [Function],
joined: [Function],
left: [Function],
ping: [Function],
ha: [Function],
authenticated: [Function],
error: [Function],
timeout: [Function],
close: [Function],
parseError: [Function],
open: [Object],
fullsetup: [Object],
all: [Object],
reconnect: [Function] },
_eventsCount: 22,
_maxListeners: undefined,
clientInfo:
{ driver: [Object],
os: [Object],
platform: 'Node.js v6.11.2, LE' },
s:
{ coreTopology: [Object],
sCapabilities: null,
clonedOptions: [Object],
reconnect: true,
emitError: true,
poolSize: 5,
storeOptions: [Object],
store: [Object],
host: 'ds131687.mlab.com',
port: 31687,
options: [Object],
sessionPool: [Object],
promiseLibrary: [Function: Promise] } } }
The connect function has changed on new version of mongodb. This should work
var MongoClient = require('mongodb').MongoClient;
var url = 'mongodb://u****:p****#ds131687.mlab.com:31687/learning_mongo';
var findDocuments = function(db, callback) {
var collection = db.collection('tours');
collection.find().toArray(function(err,docs){
if (err) throw err;
console.log(docs);
callback;
})
}
MongoClient.connect(url, function(err, client){
if (err) throw err;
// console.log("it is working");
// db.close();
findDocuments(client.db('learning_mongo'), function(){
db.close();
});
})
More documentation on this http://mongodb.github.io/node-mongodb-native/3.0/api/
I followed this question and was able to solve the error. Basically, I had to add the following modification to my index.js file:
MongoClient.connect('mongodb://localhost', function (err, client) {
if (err) throw err;
var db = client.db('mytestingdb');
db.collection('customers').findOne({}, function (findErr, result) {
if (findErr) throw findErr;
console.log(result.name);
client.close();
});
});
db.collection() is not a function in the latest version of MongoDB. First uninstall the latest version of MongoDB and then install version number 2.2.33 of MongoDB.
npm uninstall mongodb
npm install mongodb#2.2.33
Version MongoDB >= 3 - That database variable is actually the parent object of the object you are trying to access.
Connecting from the REPL works fine:
> var mongoose=require('mongoose');
undefined
> mongoose.connect('mongodb://localhost/test', function(error) {
... console.log( 'connected\n%s\n', error );
... });
returns:
{ connections:
[ { base: [Circular],
collections: {},
models: {},
replica: false,
hosts: null,
host: 'localhost',
port: 27017,
user: undefined,
pass: undefined,
name: 'test',
options: [Object],
_readyState: 2,
_closeCalled: false,
_hasOpened: false,
_listening: false,
_events: {},
db: [Object] } ],
plugins: [],
models: {},
modelSchemas: {},
options: {} }
> connected # Yes!
undefined
But connecting from a Mocha test suite does not work:
var mongoose = require( 'mongoose' );
console.log( 'connecting...' );
mongoose.connect( 'mongodb://localhost/test', function( error ) {
if( error) console.error( 'Error while connecting:\n%\n', error );
console.log( 'connected' );
});
returns:
$ mocha
connecting...
0 passing (0 ms)
Does anyone know why this not working?
Do you have any tests in your suite? If not it seems like mocha exits before mongoose gets a chance to connect. One of the features listed on the mocha page is
auto-exit to prevent "hanging" with an active loop
which may have something to do with it. You could try connecting to mongoose in the before method of your test suite e.g.
describe('test suite', function() {
before(function(done) {
mongoose.connect('mongodb://localhost/test', function(error) {
if (error) console.error('Error while connecting:\n%\n', error);
console.log('connected');
done(error);
});
});
});