Using Node 8.* and MongoDb driver mongodb#2.2.31
I am testing the my code base to see how it behaves if my MongoDB ever crashes. The way I test is to turn the MongoDB daemon off.
The catch() statement is not executing. Instead I get the mongodb driver error ReferenceError: handleCallbaak is not defined when mongo.tempUsers.add(body, token, password) executes.
Why is this? Shouldn't the catch() execute?
TempUsers.prototype.add = function(body, token) {
const user = { "email" : body.email };
return this.collection.updateOne(user,
{ $set: {
"token": token,
"createdAt": new Date(),
}
},
{
writeConcern: true,
maxTimeMS: QUERY_TIME,
upsert: true
}
);
const confirmUser = (body, password) => {
const token = uuidv4();
const result = mongo.tempUsers.add(body, token, password);
result.then(() => sendConfirmationEmail(body, token)).catch(e => console.log(e));
};
UPDATE: How my own collections object is created:
var collections = {
tempUsers: false
};
function connect(dbURI) {
return MongoClient
.connect(dbURI)
.then(function(db) {
console.log(colors
.bold('MongoDB default connection open to ' + dbURI));
initDbListeners(db);
initCollections(db);
return db;
})
.catch(function(err) {
console.log(colors
.red(err));
});
}
function initCollections(db) {
collections.tempUsers = new TempUsers(db);
}
module.exports.collections = collections;
/home/one/github/dolphin/node_modules/mongodb/lib/collection.js:1057
if(err) return handleCallbaak(callback, err, null);
^
ReferenceError: handleCallbaak is not defined
at Object.c (/home/one/github/dolphin/node_modules/mongodb/lib/collection.js:1057:13)
at Store.flush (/home/one/github/dolphin/node_modules/mongodb/lib/topology_base.js:68:30)
at Server.reconnectFailedHandler (/home/one/github/dolphin/node_modules/mongodb/lib/server.js:290:18)
at emitOne (events.js:115:13)
at Server.emit (events.js:210:7)
at Pool.<anonymous> (/home/one/github/dolphin/node_modules/mongodb-core/lib/topologies/server.js:324:14)
at emitOne (events.js:115:13)
at Pool.emit (events.js:210:7)
at Connection.<anonymous> (/home/one/github/dolphin/node_modules/mongodb-core/lib/connection/pool.js:317:16)
at emitTwo (events.js:125:13)
at Connection.emit (events.js:213:7)
at Socket.<anonymous> (/home/one/github/dolphin/node_modules/mongodb-core/lib/connection/connection.js:187:49)
at Object.onceWrapper (events.js:316:30)
at emitOne (events.js:115:13)
at Socket.emit (events.js:210:7)
at emitErrorNT (internal/streams/destroy.js:64:8)
The mongodb node_modules/mongodb/lib/collection.js file on your system is different from the released file.
Remove the /home/one/github/dolphin/node_modules/mongodb directory from your project and run npm install again.
Related
I'm learning full stack web development and was trying to connect to SQL server from my backend Node.js. I was following an online video. While running the index.js file I get the below error -
ConnectionError: Login failed for user 'systemadmin'.
at C:\Users\akunjalw\Desktop\FullStack\server\node_modules\mssql\lib\tedious\connection-pool.js:70:17
at Connection.onConnect (C:\Users\akunjalw\Desktop\FullStack\server\node_modules\tedious\lib\connection.js:1038:9)
at Object.onceWrapper (node:events:640:26)
at Connection.emit (node:events:520:28)
at Connection.emit (C:\Users\akunjalw\Desktop\FullStack\server\node_modules\tedious\lib\connection.js:1066:18)
at Parser.<anonymous> (C:\Users\akunjalw\Desktop\FullStack\server\node_modules\tedious\lib\connection.js:2574:20)
at Object.onceWrapper (node:events:639:28)
at Parser.emit (node:events:520:28)
at Readable.<anonymous> (C:\Users\akunjalw\Desktop\FullStack\server\node_modules\tedious\lib\token\token-stream-parser.js:32:12)
at Readable.emit (node:events:520:28) {
code: 'ELOGIN',
originalError: ConnectionError: Login failed for user 'systemadmin'.
at Login7TokenHandler.onErrorMessage (C:\Users\akunjalw\Desktop\FullStack\server\node_modules\tedious\lib\token\handler.js:239:19)
at Readable.<anonymous> (C:\Users\akunjalw\Desktop\FullStack\server\node_modules\tedious\lib\token\token-stream-parser.js:26:33)
at Readable.emit (node:events:520:28)
at addChunk (node:internal/streams/readable:315:12)
at readableAddChunk (node:internal/streams/readable:289:9)
at Readable.push (node:internal/streams/readable:228:10)
at next (node:internal/streams/from:98:31)
at processTicksAndRejections (node:internal/process/task_queues:96:5) {
code: 'ELOGIN',
isTransient: undefined
}
}
undefined
[nodemon] clean exit - waiting for changes before restart
The code is as follows
const sql = require("mssql");
const config = {
user: "systemadmin",
password: "R#jasthaan1212",
server: "localhost",
database: "ORG_EMPLOYEEDATA",
options: {
trustedconnection: true,
trustServerCertificate: true,
enableArithAbort: true,
instancename: "SQL2019",
},
port: 50685,
};
async function getEmployeeName() {
try {
let pool = await sql.connect(config);
let employeeData = await pool
.request()
.query("select * from dbo.EMPLOYEES_DATA");
return employeeData.recordsets;
} catch (error) {
console.log(error);
}
}
module.exports = { getEmployeeName: getEmployeeName };
const dboperations = require("./dboperations");
dboperations.getEmployeeName().then((result) => {
console.log(result);
});
Please let me know what exactly I'm missing here. I couldn't find the way to resolve this by searching in internet as well, may be I'm terrible at searching. Any help to resolve this is appreciated.
I am new to Node js programming. Trying to write a simple user create using.. code along with the stack track is given below. Appreciate any help as to what is causing this..
users-add.mjs:
'use strict';
const util = require('util');
const restify = require('restify-clients');
console.log("starting...");
var client = restify.createJsonClient({url: 'http://localhost:'+process.env.PORT, version: '*'});
console.log("starting...2 ");
client.basicAuth('them', 'D4ED43C0-8BD6-4FE2-B358-7C0E230D11EF');
client.post('/create-user', { username: "me", password: "w0rd", provider: "local",
familyName: "GUD", givenName: "RG", middleName: "Ud", emails: [], photos: []},
(err, req, res, obj) => {
console.log("starting...4 ");
if(err) {
console.log("starting...5");
console.error(err.stack);
}
else {
console.log("starting...6");
console.log('Created ' + util.inspect(obj));
}
});
console.log("starting...3 ");
Here is the error I'm getting.. Surprisingly the server side code is able to insert the record into MongoDB, and yet I get this error..
InternalServerError: {}
at Object.createHttpErr (/Users/raviguduru/node-web-dev/chapter8/users/node_modules/restify-clients/lib/helpers/errors.js:91:26)
at ClientRequest.onResponse (/Users/raviguduru/node-web-dev/chapter8/users/node_modules/restify-clients/lib/HttpClient.js:309:26)
at Object.onceWrapper (events.js:300:26)
at ClientRequest.emit (events.js:210:5)
at HTTPParser.parserOnIncomingClient [as onIncoming] (_http_client.js:583:27)
at HTTPParser.parserOnHeadersComplete (_http_common.js:115:17)
at Socket.socketOnData (_http_client.js:456:22)
at Socket.emit (events.js:210:5)
at addChunk (_stream_readable.js:309:12)
at readableAddChunk (_stream_readable.js:290:11)
Pls help.
This problem is solved now.. The internal server error comes when we have MongoDBClient calls not wrapped in try/catch blocks. After I included try/catch blocks, they went away.
I've noticed that MongoDB errors offer rather useless stack traces, pointing only within the driver's internals. The line of code in the client that triggered the error is not output:
const MongoClient = require('mongodb').MongoClient;
MongoClient.connect('...', { useNewUrlParser: true }, async (err, client) => {
try {
// some mongo client code...
// some more mongo client calls...
await client.db().collection('nonexistent').drop();
// yet more mongo client calls...
} catch (e) {
console.error(e);
}
client.close();
});
Here's the output from that:
MongoError: ns not found
at Connection.<anonymous> (/home/dandv/mongostack/node_modules/mongodb-core/lib/connection/pool.js:443:61)
at Connection.emit (events.js:200:13)
at processMessage (/home/dandv/mongostack/node_modules/mongodb-core/lib/connection/connection.js:364:10)
at TLSSocket.<anonymous> (/home/dandv/mongostack/node_modules/mongodb-core/lib/connection/connection.js:533:15)
at TLSSocket.emit (events.js:200:13)
at addChunk (_stream_readable.js:290:12)
at readableAddChunk (_stream_readable.js:271:11)
at TLSSocket.Readable.push (_stream_readable.js:226:10)
at TLSWrap.onStreamRead (internal/stream_base_commons.js:166:17) {
ok: 0,
errmsg: 'ns not found',
code: 26,
codeName: 'NamespaceNotFound',
name: 'MongoError',
[Symbol(mongoErrorContextSymbol)]: {}
}
If there's more than one mongo driver call in the try/catch block, it's impossible to tell which one generated the error.
Is there a way to have those stack traces lead up to client code?
app.get('/', function (req, res) {
var config = {
//user: 'sa',
// password: '',
server: 'localhost',
database: 'TestDB',
debug: true
};
// connect to your database
sql.connect(config, function (err) {
if (err) console.log(err);
// create Request object
var request = new sql.Request();
// query to the database and get the records
request.query('select * from userInfo', function (err, recordset) {
if (err) console.log(err)
// send records as a response
res.send(recordset);
//console.log(recordset);
sql.close();
});
});
});
I want to connect without user and password and Getting this error while executing through command prompt and there is some trusted connection query I can't find the please help
Error: Login failed for user ''.
at Connection.tedious.once.err (D:\Nodejs\UsersCreate\node_modules\mssql\lib\tedious.js:216:17)
at Object.onceWrapper (events.js:293:19)
at emitOne (events.js:96:13)
at Connection.emit (events.js:191:7)
at Connection.processLogin7Response (D:\Nodejs\UsersCreate\node_modules\tedious\lib\connection.js:1148:16)
at Connection.message (D:\Nodejs\UsersCreate\node_modules\tedious\lib\connection.js:1660:14)
at Connection.dispatchEvent (D:\Nodejs\UsersCreate\node_modules\tedious\lib\connection.js:863:38)
at MessageIO.<anonymous> (D:\Nodejs\UsersCreate\node_modules\tedious\lib\connection.js:757:18)
at emitNone (events.js:86:13)
at MessageIO.emit (events.js:188:7)
code: 'ELOGIN',
originalError:
{ ConnectionError: Login failed for user ''.
at ConnectionError (D:\Nodejs\UsersCreate\node_modules\tedious\lib\errors.js:12:12)
at Parser.<anonymous> (D:\Nodejs\UsersCreate\node_modules\tedious\lib\connection.js:507:33)
at emitOne (events.js:96:13)
at Parser.emit (events.js:191:7)
at Parser.<anonymous> (D:\Nodejs\UsersCreate\node_modules\tedious\lib\token\token-stream-parser.js:54:15)
at emitOne (events.js:96:13)
at Parser.emit (events.js:191:7)
at addChunk (D:\Nodejs\UsersCreate\node_modules\tedious\node_modules\readable-stream\lib\_stream_readable.js:284:12)
at readableAddChunk (D:\Nodejs\UsersCreate\node_modules\tedious\node_modules\readable-stream\lib\_stream_readable.js:271:11)
at Parser.Readable.push (D:\Nodejs\UsersCreate\node_modules\tedious\node_modules\readable-stream\lib\_stream_readable.js:238:10) message: 'Login failed for user \'\'.', code: 'ELOGIN' },
name: 'ConnectionError' }
{ ConnectionError: Connection is closed.
at Request._query (D:\Nodejs\UsersCreate\node_modules\mssql\lib\base.js:1299:37)
at Request._query (D:\Nodejs\UsersCreate\node_modules\mssql\lib\tedious.js:497:11)
at Request.query (D:\Nodejs\UsersCreate\node_modules\mssql\lib\base.js:1242:12)
at D:\Nodejs\UsersCreate\app.js:119:17
at _poolCreate.then.catch.err (D:\Nodejs\UsersCreate\node_modules\mssql\lib\base.js:269:7)
at process._tickCallback (internal/process/next_tick.js:109:7) code: 'ECONNCLOSED', name: 'ConnectionError' }
GET / 200 36.940 ms - -
Please help me on this and want to connect this database using window authentication
You can try with:
options: {
trustedConnection: true
}
First install NPM Package,
npm install msnodesqlv8
Then change your config variable as,
const sql = require('mssql/msnodesqlv8')
var config = {
server: 'localhost',
driver: 'msnodesqlv8',
database: 'TestDB',
debug: true,
options: {
trustedConnection: true
}
};
When attempting to save a document this error is thrown:
/Users/home/Documents/web/thp/modules/thp_db/node_modules/mongoose/node_modules/mongodb/lib/utils.js:98
process.nextTick(function() { throw err; });
^
TypeError: _this[i].emit is not a function
at EventEmitter.notify (/Users/home/Documents/web/thp/modules/thp_db/node_modules/mongoose/lib/types/documentarray.js:238:18)
at emitOne (events.js:82:20)
at EventEmitter.emit (events.js:169:7)
at Document.(anonymous function) [as emit] (/Users/home/Documents/web/thp/modules/thp_db/node_modules/mongoose/lib/document.js:93:44)
at EventEmitter.<anonymous> (/Users/home/Documents/web/thp/modules/thp_db/node_modules/mongoose/lib/schema/embedded.js:31:15)
at emitTwo (events.js:92:20)
at EventEmitter.emit (events.js:172:7)
at model.Document.(anonymous function) [as emit] (/Users/home/Documents/web/thp/modules/thp_db/node_modules/mongoose/lib/document.js:93:44)
at /Users/home/Documents/web/thp/modules/thp_db/node_modules/mongoose/lib/model.js:227:11
at /Users/home/Documents/web/thp/modules/thp_db/node_modules/mongoose/lib/model.js:135:7
at /Users/home/Documents/web/thp/modules/thp_db/node_modules/mongoose/node_modules/mongodb/lib/collection.js:504:5
at /Users/home/Documents/web/thp/modules/thp_db/node_modules/mongoose/node_modules/mongodb/lib/collection.js:666:5
at handleCallback (/Users/home/Documents/web/thp/modules/thp_db/node_modules/mongoose/node_modules/mongodb/lib/utils.js:96:12)
at /Users/home/Documents/web/thp/modules/thp_db/node_modules/mongoose/node_modules/mongodb/lib/bulk/unordered.js:473:9
at handleCallback (/Users/home/Documents/web/thp/modules/thp_db/node_modules/mongoose/node_modules/mongodb/lib/utils.js:96:12)
at resultHandler (/Users/home/Documents/web/thp/modules/thp_db/node_modules/mongoose/node_modules/mongodb/lib/bulk/unordered.js:420:5)
at commandCallback (/Users/home/Documents/web/thp/modules/thp_db/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/server.js:1246:9)
at Callbacks.emit (/Users/home/Documents/web/thp/modules/thp_db/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/server.js:119:3)
at null.messageHandler (/Users/home/Documents/web/thp/modules/thp_db/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/server.js:397:23)
at Socket.<anonymous> (/Users/home/Documents/web/thp/modules/thp_db/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/connection/connection.js:302:22)
at emitOne (events.js:77:13)
at Socket.emit (events.js:169:7)
at readableAddChunk (_stream_readable.js:153:18)
at Socket.Readable.push (_stream_readable.js:111:10)
at TCP.onread (net.js:536:20)
Code leading to save looks like this:
var db = req.app.locals.db;
var league = new db.League();
// league is populated here
// ================
// GIVE LEAGUE _id (auto increment)
// ================
db.Counter.findByIdAndUpdate('League',
{ $inc: { n: 1 } },
{ new: true },
function(err, counter){
if(err) return log.error('League _id set error', err);
league._id = counter.n;
// ================
// INTO DB: CODE RUNS TO HERE
// ================
league.save(function(err, new_league) {
// DOES NOT REACH HERE!
if (err) {
log.error('league DB entry error:', err);
return res.status(200).end('Error creating league');
}
console.log('SAVED LEAGUE', util.inspect(new_league, false, null));
res.status(200).end('Thank you');
});
}
);
Strange thing is that this worked fine last night, and unless I sleepwalked and logged in, nothing was changed.
the db variable is a collection of models.
Any help would be much appreciated.
Turns out that the error is thrown depending on which inputs of the submission form are filled out. Haven't the time to determine which exactly at the moment, but will update here when I do.
UPDATE: my league var was populated by a JSON object parsed from incoming form data. One of the properties was thoughtlessly called .on, which was fooling with the standard event listening notation .on. Silly mistake! Always is.