NodeJs mssql connection returning undefined from .Request() - node.js

I'm having trouble getting a working connection via nmp's mssql package.
Here's a quick look at my code:
var sql = require('mssql');
var sqlConfig = {
user: 'NodeUser',
password: 'test',
server: '10.211.55.3',
database: 'NodeJs'
}
sql.connect(sqlConfig, function(err){
if(err != null)
console.log(err);
console.log(sql);
});
Which seems to connect fine, but when I try to use it (in a route class):
var sql = require('mssql');
bookRouter.route('/')
.get(function(req, res){
var req = sql.Request();
req.query('select * from books', function(err, recordset){
console.log(recordset);
});
res.render('BookListView', {
title: 'Hello from Books',
nav: nav,
books: books
});
});
I get "TypeError: Cannot read property 'query' of undefined" on the req.query line. It seems like an issue with the connection? The only useful thing I could think to pull was the result of the "console.log(sql);" line above:
{ connect: [Function],
close: [Function],
on: [Function],
Connection:
{ [Function: Connection]
EventEmitter:
{ [Function: EventEmitter]
EventEmitter: [Circular],
usingDomains: false,
defaultMaxListeners: [Getter/Setter],
init: [Function],
listenerCount: [Function] },
usingDomains: false,
defaultMaxListeners: 10,
init: [Function],
listenerCount: [Function],
__super__:
EventEmitter {
domain: undefined,
_events: undefined,
_maxListeners: undefined,
setMaxListeners: [Function: setMaxListeners],
getMaxListeners: [Function: getMaxListeners],
emit: [Function: emit],
addListener: [Function: addListener],
on: [Function: addListener],
once: [Function: once],
removeListener: [Function: removeListener],
removeAllListeners: [Function: removeAllListeners],
listeners: [Function: listeners],
listenerCount: [Function: listenerCount] } },
Transaction:
{ [Function: Transaction]
EventEmitter:
{ [Function: EventEmitter]
EventEmitter: [Circular],
usingDomains: false,
defaultMaxListeners: [Getter/Setter],
init: [Function],
listenerCount: [Function] },
usingDomains: false,
defaultMaxListeners: 10,
init: [Function],
listenerCount: [Function],
__super__:
EventEmitter {
domain: undefined,
_events: undefined,
_maxListeners: undefined,
setMaxListeners: [Function: setMaxListeners],
getMaxListeners: [Function: getMaxListeners],
emit: [Function: emit],
addListener: [Function: addListener],
on: [Function: addListener],
once: [Function: once],
removeListener: [Function: removeListener],
removeAllListeners: [Function: removeAllListeners],
listeners: [Function: listeners],
listenerCount: [Function: listenerCount] } },
Request:
{ [Function: Request]
EventEmitter:
{ [Function: EventEmitter]
EventEmitter: [Circular],
usingDomains: false,
defaultMaxListeners: [Getter/Setter],
init: [Function],
listenerCount: [Function] },
usingDomains: false,
defaultMaxListeners: 10,
init: [Function],
listenerCount: [Function],
__super__:
EventEmitter {
domain: undefined,
_events: undefined,
_maxListeners: undefined,
setMaxListeners: [Function: setMaxListeners],
getMaxListeners: [Function: getMaxListeners],
emit: [Function: emit],
addListener: [Function: addListener],
on: [Function: addListener],
once: [Function: once],
removeListener: [Function: removeListener],
removeAllListeners: [Function: removeAllListeners],
listeners: [Function: listeners],
listenerCount: [Function: listenerCount] } },
Table: { [Function: Table] fromRecordset: [Function] },
PreparedStatement:
{ [Function: PreparedStatement]
EventEmitter:
{ [Function: EventEmitter]
EventEmitter: [Circular],
usingDomains: false,
defaultMaxListeners: [Getter/Setter],
init: [Function],
listenerCount: [Function] },
usingDomains: false,
defaultMaxListeners: 10,
init: [Function],
listenerCount: [Function],
__super__:
EventEmitter {
domain: undefined,
_events: undefined,
_maxListeners: undefined,
setMaxListeners: [Function: setMaxListeners],
getMaxListeners: [Function: getMaxListeners],
emit: [Function: emit],
addListener: [Function: addListener],
on: [Function: addListener],
once: [Function: once],
removeListener: [Function: removeListener],
removeAllListeners: [Function: removeAllListeners],
listeners: [Function: listeners],
listenerCount: [Function: listenerCount] } },
ConnectionError:
{ [Function: ConnectionError]
captureStackTrace: [Function: captureStackTrace],
stackTraceLimit: 10,
prepareStackTrace: undefined,
__super__: [Error] },
TransactionError:
{ [Function: TransactionError]
captureStackTrace: [Function: captureStackTrace],
stackTraceLimit: 10,
prepareStackTrace: undefined,
__super__: [Error] },
RequestError:
{ [Function: RequestError]
captureStackTrace: [Function: captureStackTrace],
stackTraceLimit: 10,
prepareStackTrace: undefined,
__super__: [Error] },
PreparedStatementError:
{ [Function: PreparedStatementError]
captureStackTrace: [Function: captureStackTrace],
stackTraceLimit: 10,
prepareStackTrace: undefined,
__super__: [Error] },
ISOLATION_LEVEL:
{ READ_UNCOMMITTED: 1,
READ_COMMITTED: 2,
REPEATABLE_READ: 3,
SERIALIZABLE: 4,
SNAPSHOT: 5 },
DRIVERS: [ 'msnodesql', 'tedious', 'tds', 'msnodesqlv8' ],
TYPES:
{ VarChar: [sql.VarChar],
NVarChar: [sql.NVarChar],
Text: [sql.Text],
Int: [sql.Int],
BigInt: [sql.BigInt],
TinyInt: [sql.TinyInt],
SmallInt: [sql.SmallInt],
Bit: [sql.Bit],
Float: [sql.Float],
Numeric: [sql.Numeric],
Decimal: [sql.Decimal],
Real: [sql.Real],
Date: [sql.Date],
DateTime: [sql.DateTime],
DateTime2: [sql.DateTime2],
DateTimeOffset: [sql.DateTimeOffset],
SmallDateTime: [sql.SmallDateTime],
Time: [sql.Time],
UniqueIdentifier: [sql.UniqueIdentifier],
SmallMoney: [sql.SmallMoney],
Money: [sql.Money],
Binary: [sql.Binary],
VarBinary: [sql.VarBinary],
Image: [sql.Image],
Xml: [sql.Xml],
Char: [sql.Char],
NChar: [sql.NChar],
NText: [sql.NText],
TVP: [sql.TVP],
UDT: [sql.UDT],
Geography: [sql.Geography],
Geometry: [sql.Geometry],
Variant: [sql.Variant] },
MAX: 65535,
map:
[ { js: [Function: String], sql: [sql.NVarChar] },
{ js: [Function: Number], sql: [sql.Int] },
{ js: [Function: Boolean], sql: [sql.Bit] },
{ js: [Function: Date], sql: [sql.DateTime] },
{ js: [Object], sql: [sql.VarBinary] },
{ js: [Object], sql: [sql.TVP] },
register: [Function] ],
fix: true,
Promise: [Function: Promise],
VarChar: [sql.VarChar],
VARCHAR: [sql.VarChar],
NVarChar: [sql.NVarChar],
NVARCHAR: [sql.NVarChar],
Text: [sql.Text],
TEXT: [sql.Text],
Int: [sql.Int],
INT: [sql.Int],
BigInt: [sql.BigInt],
BIGINT: [sql.BigInt],
TinyInt: [sql.TinyInt],
TINYINT: [sql.TinyInt],
SmallInt: [sql.SmallInt],
SMALLINT: [sql.SmallInt],
Bit: [sql.Bit],
BIT: [sql.Bit],
Float: [sql.Float],
FLOAT: [sql.Float],
Numeric: [sql.Numeric],
NUMERIC: [sql.Numeric],
Decimal: [sql.Decimal],
DECIMAL: [sql.Decimal],
Real: [sql.Real],
REAL: [sql.Real],
Date: [sql.Date],
DATE: [sql.Date],
DateTime: [sql.DateTime],
DATETIME: [sql.DateTime],
DateTime2: [sql.DateTime2],
DATETIME2: [sql.DateTime2],
DateTimeOffset: [sql.DateTimeOffset],
DATETIMEOFFSET: [sql.DateTimeOffset],
SmallDateTime: [sql.SmallDateTime],
SMALLDATETIME: [sql.SmallDateTime],
Time: [sql.Time],
TIME: [sql.Time],
UniqueIdentifier: [sql.UniqueIdentifier],
UNIQUEIDENTIFIER: [sql.UniqueIdentifier],
SmallMoney: [sql.SmallMoney],
SMALLMONEY: [sql.SmallMoney],
Money: [sql.Money],
MONEY: [sql.Money],
Binary: [sql.Binary],
BINARY: [sql.Binary],
VarBinary: [sql.VarBinary],
VARBINARY: [sql.VarBinary],
Image: [sql.Image],
IMAGE: [sql.Image],
Xml: [sql.Xml],
XML: [sql.Xml],
Char: [sql.Char],
CHAR: [sql.Char],
NChar: [sql.NChar],
NCHAR: [sql.NChar],
NText: [sql.NText],
NTEXT: [sql.NText],
TVP: [sql.TVP],
UDT: [sql.UDT],
Geography: [sql.Geography],
GEOGRAPHY: [sql.Geography],
Geometry: [sql.Geometry],
GEOMETRY: [sql.Geometry],
Variant: [sql.Variant],
VARIANT: [sql.Variant],
pool: { max: 10, min: 0, idleTimeoutMillis: 30000 },
connection: { userName: '', password: '', server: '' },
init: [Function] }
I can't help but notice the lack of credentials here. Any thoughts? Thanks.

Looks like an issue of asynchronisity, try doing it on the request directly, like the mssql npm example:
var sql = require('mssql');
bookRouter.route('/')
.get(function(req, res){
sql.Request().query('select * from books')
.then(function(recordset){
console.log(recordset);
res.render('BookListView', {
title: 'Hello from Books',
nav: nav,
books: books
});
}).catch(function(err){
// some error handling
});
});

Related

Mongoose Difficulty in displaying time stamps

I have been Recently Working on Mongoose To connect with the MongoDB with Node application.
I have Used Schemas to build the model and set the timestamps to true.
But When i try to run the node application it displays a very long message and the time stamps are empty in the terminal but displays when copied and pasted in text editor.
I want the output to be short to only display the documents available in my collection.
Here is My code
index.js file
const mongoose = require('mongoose');
const Dishes = require('./models/dishes')
const url = 'mongodb://localhost:27017/conFusion';
const connect = mongoose.connect(url);
connect.then((db) => {
console.log('Connected correctly to server');
Dishes.create({
name: 'Uthapizzas',
description: 'Test'
})
.then((dish) => {
console.log(dish);
return Dishes.findByIdAndUpdate(dish._id,{
$set: { description: 'Updated Test'}
},{
new: true//return the updated dish
}).exec();
})
.then((dish) => {
console.log(dish);
dish.comments.push({
rating: 5,
comment: 'I\'m getting a sinking feeling!',
author: 'Leonardo di Carpaccio'
});
return dish.save();
})
.then((dish) => {
console.log(dish);
return Dishes.remove({});
})
.then(() => {
return mongoose.connection.close();
})
.catch((err) => {
console.log(err);
});
dishes.js file
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const commentSchema = new Schema({
rating: {
type: Number,
min: 1,
max: 5,
required: true
},
comment: {
type: String,
required: true
},
author:{
type: String,
required: true
}
}, {
timestamps: true
});
const dishSchema = new Schema({
name: {
type: String,
required: true,
unique: true
},
description: {
type: String,
required: true
},
comments:[commentSchema]
},
{
timestamps: true
}
);
var Dishes = mongoose.model('Dish', dishSchema);
module.exports = Dishes;
Here is My output
<ref *1> model {
'$__': InternalCache {
strictMode: true,
selected: undefined,
shardval: undefined,
saveError: undefined,
validationError: undefined,
adhocPaths: undefined,
removing: undefined,
inserting: true,
saving: undefined,
version: undefined,
getters: {},
_id: 63563fab8405ad299448f321,
populate: undefined,
populated: undefined,
wasPopulated: false,
scope: undefined,
activePaths: StateMachine {
paths: [Object],
states: [Object],
stateNames: [Array],
map: [Function (anonymous)]
},
pathsToScopes: {},
session: null,
ownerDocument: undefined,
fullPath: undefined,
emitter: EventEmitter {
_events: [Object: null prototype],
_eventsCount: 2,
_maxListeners: 0,
[Symbol(kCapture)]: false
},
'$options': {}
},
isNew: false,
errors: undefined,
_doc: {
_id: 63563fab8405ad299448f321,
name: 'Uthapizzas',
description: 'Test',
comments: CoreMongooseArray(0) [
_path: 'comments',
toBSON: [Function: toBSON],
_atomics: {},
_parent: [Circular *1],
_cast: [Function: _cast],
_markModified: [Function: _markModified],
_registerAtomic: [Function: _registerAtomic],
'$__getAtomics': [Function: $__getAtomics],
hasAtomics: [Function: hasAtomics],
_mapCast: [Function: _mapCast],
push: [Function: push],
nonAtomicPush: [Function: nonAtomicPush],
'$pop': [Function: $pop],
pop: [Function: pop],
'$shift': [Function: $shift],
shift: [Function: shift],
pull: [Function: pull],
splice: [Function: splice],
unshift: [Function: unshift],
sort: [Function: sort],
addToSet: [Function: addToSet],
set: [Function: set],
toObject: [Function: toObject],
inspect: [Function: inspect],
indexOf: [Function: indexOf],
remove: [Function: pull],
id: [Function: id],
create: [Function: create],
notify: [Function: notify],
isMongooseDocumentArray: true,
validators: [],
_schema: [DocumentArray],
_handlers: [Object]
],
createdAt: 2022-10-24T07:32:59.266Z,
updatedAt: 2022-10-24T07:32:59.266Z,
__v: 0
}
}
<ref *1> model {
'$__': InternalCache {
strictMode: true,
selected: {},
shardval: undefined,
saveError: undefined,
validationError: undefined,
adhocPaths: undefined,
removing: undefined,
inserting: undefined,
saving: undefined,
version: undefined,
getters: {},
_id: 63563fab8405ad299448f321,
populate: undefined,
populated: undefined,
wasPopulated: false,
scope: undefined,
activePaths: StateMachine {
paths: [Object],
states: [Object],
stateNames: [Array]
},
pathsToScopes: {},
session: undefined,
ownerDocument: undefined,
fullPath: undefined,
emitter: EventEmitter {
_events: [Object: null prototype],
_eventsCount: 2,
_maxListeners: 0,
[Symbol(kCapture)]: false
},
'$options': { skipId: true, isNew: false, skipDefaults: [Object] }
},
isNew: false,
errors: undefined,
_doc: {
_id: 63563fab8405ad299448f321,
name: 'Uthapizzas',
description: 'Updated Test',
comments: CoreMongooseArray(0) [
_path: 'comments',
toBSON: [Function: toBSON],
_atomics: {},
_parent: [Circular *1],
_cast: [Function: _cast],
_markModified: [Function: _markModified],
_registerAtomic: [Function: _registerAtomic],
'$__getAtomics': [Function: $__getAtomics],
hasAtomics: [Function: hasAtomics],
_mapCast: [Function: _mapCast],
push: [Function: push],
nonAtomicPush: [Function: nonAtomicPush],
'$pop': [Function: $pop],
pop: [Function: pop],
'$shift': [Function: $shift],
shift: [Function: shift],
pull: [Function: pull],
splice: [Function: splice],
unshift: [Function: unshift],
sort: [Function: sort],
addToSet: [Function: addToSet],
set: [Function: set],
toObject: [Function: toObject],
inspect: [Function: inspect],
indexOf: [Function: indexOf],
remove: [Function: pull],
id: [Function: id],
create: [Function: create],
notify: [Function: notify],
isMongooseDocumentArray: true,
validators: [],
_schema: [DocumentArray],
_handlers: [Object]
],
createdAt: 2022-10-24T07:32:59.266Z,
updatedAt: 2022-10-24T07:32:59.287Z,
__v: 0
},
'$init': true
}
<ref *1> model {
'$__': InternalCache {
strictMode: true,
selected: {},
shardval: undefined,
saveError: undefined,
validationError: undefined,
adhocPaths: undefined,
removing: undefined,
inserting: false,
saving: undefined,
version: undefined,
getters: {},
_id: 63563fab8405ad299448f321,
populate: undefined,
populated: undefined,
wasPopulated: false,
scope: undefined,
activePaths: StateMachine {
paths: [Object],
states: [Object],
stateNames: [Array],
map: [Function (anonymous)]
},
pathsToScopes: { comments: [Circular *1] },
session: undefined,
ownerDocument: undefined,
fullPath: undefined,
emitter: EventEmitter {
_events: [Object: null prototype],
_eventsCount: 2,
_maxListeners: 0,
[Symbol(kCapture)]: false
},
'$options': { skipId: true, isNew: false, skipDefaults: [Object] }
},
isNew: false,
errors: undefined,
_doc: {
_id: 63563fab8405ad299448f321,
name: 'Uthapizzas',
description: 'Updated Test',
comments: CoreMongooseArray(1) [
[EmbeddedDocument],
_path: 'comments',
toBSON: [Function: toBSON],
_atomics: {},
_parent: [Circular *1],
_cast: [Function: _cast],
_markModified: [Function: _markModified],
_registerAtomic: [Function: _registerAtomic],
'$__getAtomics': [Function: $__getAtomics],
hasAtomics: [Function: hasAtomics],
_mapCast: [Function: _mapCast],
push: [Function: push],
nonAtomicPush: [Function: nonAtomicPush],
'$pop': [Function: $pop],
pop: [Function: pop],
'$shift': [Function: $shift],
shift: [Function: shift],
pull: [Function: pull],
splice: [Function: splice],
unshift: [Function: unshift],
sort: [Function: sort],
addToSet: [Function: addToSet],
set: [Function: set],
toObject: [Function: toObject],
inspect: [Function: inspect],
indexOf: [Function: indexOf],
remove: [Function: pull],
id: [Function: id],
create: [Function: create],
notify: [Function: notify],
isMongooseDocumentArray: true,
validators: [],
_schema: [DocumentArray],
_handlers: [Object]
],
createdAt: 2022-10-24T07:32:59.266Z,
updatedAt: 2022-10-24T07:32:59.308Z,
__v: 1
},
'$init': true
}
Can You Please Help me in resolving this issue.
Why i am getting this much lines of output and why my time stamps are not displaying in the output(They are Displaying when copied) and the output looks very clumsy.
I only need the output which document i have inserted into the database and need the time stamps.
I am not able to access the time stamps also.
I am using mongo v5
Thank you in advance!!
You should log your plaing javascript object, not the document. In order to do this, you should call console.log(dish.toJSON()).

How do I deactivate the express server information log in node.js?

I'm trying to host a simple express server with node.js on replit.com, which so far works quite well. However, whenever I start the application, there is some seriously annoying console output:
Server {
insecureHTTPParser: undefined,
_events: [Object: null prototype] {
connection: [Function: connectionListener],
close: [Function: bound close],
listening: [ [Function: bound init], [Function] ],
upgrade: [Function],
request: [Function]
},
_eventsCount: 5,
_maxListeners: undefined,
_connections: 0,
_handle: TCP {
reading: false,
onconnection: [Function: onconnection],
[Symbol(owner_symbol)]: [Circular]
},
Server {
insecureHTTPParser: undefined,
_events: [Object: null prototype] {
request: [Function: app] EventEmitter {
_events: [Object: null prototype],
_eventsCount: 1,
_maxListeners: undefined,
setMaxListeners: [Function: setMaxListeners],
getMaxListeners: [Function: getMaxListeners],
emit: [Function],
addListener: [Function: addListener],
on: [Function: addListener],
prependListener: [Function: prependListener],
once: [Function: once],
prependOnceListener: [Function: prependOnceListener],
removeListener: [Function: removeListener],
off: [Function: removeListener],
removeAllListeners: [Function: removeAllListeners],
listeners: [Function: listeners],
rawListeners: [Function: rawListeners],
listenerCount: [Function: listenerCount],
eventNames: [Function: eventNames],
init: [Function: init],
defaultConfiguration: [Function: defaultConfiguration],
lazyrouter: [Function: lazyrouter],
handle: [Function: handle],
use: [Function: use],
route: [Function: route],
engine: [Function: engine],
param: [Function: param],
set: [Function: set],
path: [Function: path],
enabled: [Function: enabled],
disabled: [Function: disabled],
enable: [Function: enable],
disable: [Function: disable],
acl: [Function],
bind: [Function],
checkout: [Function],
connect: [Function],
copy: [Function],
delete: [Function],
get: [Function],
head: [Function],
link: [Function],
lock: [Function],
'm-search': [Function],
merge: [Function],
mkactivity: [Function],
mkcalendar: [Function],
mkcol: [Function],
move: [Function],
notify: [Function],
options: [Function],
patch: [Function],
post: [Function],
pri: [Function],
propfind: [Function],
proppatch: [Function],
purge: [Function],
put: [Function],
rebind: [Function],
report: [Function],
search: [Function],
source: [Function],
subscribe: [Function],
trace: [Function],
unbind: [Function],
unlink: [Function],
unlock: [Function],
unsubscribe: [Function],
all: [Function: all],
del: [Function],
render: [Function: render],
listen: [Function: listen],
request: [IncomingMessage],
response: [ServerResponse],
cache: {},
engines: {},
settings: [Object],
locals: [Object: null prototype],
mountpath: '/',
_router: [Function]
},
connection: [Function: connectionListener],
listening: [Function: bound onceWrapper] { listener: [Function] }
},
_eventsCount: 3,
_maxListeners: undefined,
_connections: 0,
_handle: TCP {
reading: false,
onconnection: [Function: onconnection],
[Symbol(owner_symbol)]: [Circular]
},
_usingWorkers: false,
Server {
insecureHTTPParser: undefined,
_events: [Object: null prototype] {
request: [Function: app] EventEmitter {
_events: [Object: null prototype],
_eventsCount: 1,
_maxListeners: undefined,
setMaxListeners: [Function: setMaxListeners],
getMaxListeners: [Function: getMaxListeners],
emit: [Function],
addListener: [Function: addListener],
on: [Function: addListener],
prependListener: [Function: prependListener],
once: [Function: once],
prependOnceListener: [Function: prependOnceListener],
removeListener: [Function: removeListener],
off: [Function: removeListener],
removeAllListeners: [Function: removeAllListeners],
listeners: [Function: listeners],
rawListeners: [Function: rawListeners],
listenerCount: [Function: listenerCount],
eventNames: [Function: eventNames],
init: [Function: init],
defaultConfiguration: [Function: defaultConfiguration],
lazyrouter: [Function: lazyrouter],
handle: [Function: handle],
use: [Function: use],
route: [Function: route],
engine: [Function: engine],
param: [Function: param],
set: [Function: set],
path: [Function: path],
enabled: [Function: enabled],
disabled: [Function: disabled],
enable: [Function: enable],
disable: [Function: disable],
acl: [Function],
bind: [Function],
checkout: [Function],
connect: [Function],
copy: [Function],
delete: [Function],
get: [Function],
head: [Function],
link: [Function],
lock: [Function],
'm-search': [Function],
merge: [Function],
mkactivity: [Function],
mkcalendar: [Function],
mkcol: [Function],
move: [Function],
notify: [Function],
options: [Function],
patch: [Function],
post: [Function],
pri: [Function],
propfind: [Function],
proppatch: [Function],
purge: [Function],
put: [Function],
rebind: [Function],
report: [Function],
search: [Function],
source: [Function],
subscribe: [Function],
trace: [Function],
unbind: [Function],
unlink: [Function],
unlock: [Function],
unsubscribe: [Function],
all: [Function: all],
del: [Function],
render: [Function: render],
listen: [Function: listen],
request: [IncomingMessage],
response: [ServerResponse],
cache: {},
engines: {},
settings: [Object],
locals: [Object: null prototype],
mountpath: '/',
_router: [Function]
},
connection: [Function: connectionListener],
listening: [Function: bound onceWrapper] { listener: [Function] }
},
_eventsCount: 3,
_maxListeners: undefined,
_connections: 0,
_handle: TCP {
reading: false,
onconnection: [Function: onconnection],
[Symbol(owner_symbol)]: [Circular]
},
_usingWorkers: false,
Server {
insecureHTTPParser: undefined,
_events: [Object: null prototype] {
connection: [Function: connectionListener],
close: [Function: bound close],
listening: [ [Function: bound init], [Function] ],
upgrade: [Function],
request: [Function]
},
_eventsCount: 5,
_maxListeners: undefined,
_connections: 0,
_handle: TCP {
reading: false,
onconnection: [Function: onconnection],
[Symbol(owner_symbol)]: [Circular]
},
_usingWorkers: false,
_workers: [],
_unref: false,
allowHalfOpen: true,
pauseOnConnect: false,
httpAllowHalfOpen: false,
timeout: 120000,
keepAliveTimeout: 5000,
maxHeadersCount: null,
headersTimeout: 60000,
_connectionKey: '6::::800',
[Symbol(IncomingMessage)]: [Function: IncomingMessage],
[Symbol(ServerResponse)]: [Function: ServerResponse],
[Symbol(kCapture)]: false,
[Symbol(asyncId)]: 4
}
here is my code:
const fs = require("fs");
const express = require('express');
const app = express();
const server = require('http').createServer(app);
app.get('/', (req, res) => {
res.setHeader('Content-type','text/html');
res.write(fs.readFileSync(__dirname + '/index.html'));
res.end();
});
app.get("/pages/:page", (req, res) => {
let page = req.params.page;
res.setHeader('Content-type','text/html');
res.write(fs.readFileSync(`${__dirname}/pages/${page}.html`));
res.end();
})
server.listen(800, () => {
console.log('listening on *:800');
});
How do I deactivate this? I don't want to disable console.log() itself. I believe i had the same issue a while ago, but can't remember the fix - if it wasn't just something i fixed by accident. I tried removing different portions of my code without luck and i also cannot find any similar issues online.
This is caused by replit.com echoing command results to the console.
A simple workaround is like so:
const fs = require("fs");
const express = require('express');
const app = express();
const server = require('http').createServer(app);
let {} = app.get('/', (req, res) => {
res.setHeader('Content-type','text/html');
res.write(fs.readFileSync(__dirname + '/index.html'));
res.end();
});
let {} = app.get("/pages/:page", (req, res) => {
let page = req.params.page;
res.setHeader('Content-type','text/html');
res.write(fs.readFileSync(`${__dirname}/pages/${page}.html`));
res.end();
})
let {} = server.listen(80, () => {
console.log('listening on *:80');
});
It's the app.get and server.listen calls that are returning a server object (this then gets logged).
There should be some configuration in replit.com to find this setting and change it (e.g. don't echo command results to the console), I haven't found it yet, but it's probably a better fix.

find and findone giving me model contents instead of records

I am trying to fetch one record from Mongo using the following code.
I have created a schema in another file
const mongoose = require('mongoose');
const appData = require('../../../core/utilities/appData.js');
const Schema = mongoose.Schema;
const clientListingSchema = new Schema({
...});
const clientListingsModel = mongoose.model('clientlistings', clientListingSchema);
module.exports = clientListingsModel;
And have imported the above in another file
const clientListingModel = require('./../models/clientListing');
clientListingModel.findOne({'_id': client_listings_id}).then((client_listing) => {
console.log(client_listing);
});
But I am getting something like this
model {
'$__': InternalCache {
strictMode: true,
selected: {},
shardval: undefined,
saveError: undefined,
validationError: undefined,
adhocPaths: undefined,
removing: undefined,
inserting: undefined,
version: undefined,
getters: {},
_id: 5dd4de69c7d3b8585464dadd,
populate: undefined,
populated: undefined,
wasPopulated: false,
scope: undefined,
activePaths: StateMachine {
paths: [Object],
states: [Object],
stateNames: [Array]
},
pathsToScopes: {},
ownerDocument: undefined,
fullPath: undefined,
emitter: EventEmitter {
_events: [Object: null prototype] {},
_eventsCount: 0,
_maxListeners: 0
},
'$options': true
},
isNew: false,
errors: undefined,
_doc: {
number: 3,
hub_coordinates: [
0,
0,
toBSON: [Function: toBSON],
_atomics: {},
_parent: [Circular],
_cast: [Function: _cast],
_markModified: [Function: _markModified],
_registerAtomic: [Function: _registerAtomic],
'$__getAtomics': [Function: $__getAtomics],
hasAtomics: [Function: hasAtomics],
_mapCast: [Function: _mapCast],
push: [Function: push],
nonAtomicPush: [Function: nonAtomicPush],
'$pop': [Function: $pop],
pop: [Function: pop],
'$shift': [Function: $shift],
shift: [Function: shift],
pull: [Function: pull],
splice: [Function: splice],
unshift: [Function: unshift],
sort: [Function: sort],
addToSet: [Function: addToSet],
set: [Function: set],
toObject: [Function: toObject],
inspect: [Function: inspect],
indexOf: [Function: indexOf],
remove: [Function: pull],
_path: 'hub_coordinates',
isMongooseArray: true,
validators: [],
_schema: [SchemaArray]
],
...
},
'$init': true
}
Need help figuring out how I can get only the record and not model contents.
Any help figuring this out is appreciated.
You can use lean
By default, Mongoose queries return an instance of the Mongoose Document class. Documents are much heavier than vanilla JavaScript objects, because they have a lot of internal state for change tracking.
Enabling the lean option tells Mongoose to skip instantiating a full Mongoose document and just give you the POJO.
change your code as below
clientListingModel.findOne({'_id': client_listings_id}).lean().then((client_listing) => {}
Hope it will help you.
Try for the following:
JSON.parse(JSON.stringify(client_listing))

How to get values from a mongodb cursor from a collection with elements

I'm trying to build a live chart out of a simple mongo colection, using Raspberry Pi 2 with dietPi (DietPi v6.22.3), mongodb and nodejs.
What I'm trying to do is to get data from the db using something like:
var express = require('express');
var app = express();
var MongoClient = require('mongodb').MongoClient;
var url = 'mongodb://localhost:27017/DB_A';
var str = "";
app.route('/PAGE_A').get(function (req, res) {
MongoClient.connect(url, function (err, db) {
if (err) {
console.log(err);
} else {
console.log("Connected to db");
var cursor = db.collection('COL_A').find();
console.log(cursor);
//noinspection JSDeprecatedSymbols
cursor.each(function (err, item) {
if (item != null) {
str = str + " DateTime " + item.dt + " - Users: " + item.users + " </br>";
}
});
res.send(str);
db.close();
}
});
});
var server = app.listen(8080, function () {});
Running node app.js and accessing the designated IP:8080/page_A I get the "Connected to db" message but no expected data from the cursor is being printed, except for its parameters I used for this question.
The collection is not empty. I can use DB_A and get elements from db.COL_A.find()...
This is what I get printed in the console when I "npm start" and access IP/PAGE_A:
Connected to db
Cursor {
db:
Db {
_events: [Object: null prototype] {},
_eventsCount: 0,
_maxListeners: undefined,
databaseName: 'DB_A',
serverConfig:
Server {
_events: [Object: null prototype] {},
_eventsCount: 0,
_maxListeners: undefined,
_callBackStore: [CallbackStore],
host: 'localhost',
port: 27017,
options: [Object],
internalMaster: true,
connected: true,
poolSize: 5,
disableDriverBSONSizeCheck: false,
slaveOk: undefined,
_used: true,
replicasetInstance: null,
ssl: false,
sslValidate: false,
sslCA: null,
sslCert: undefined,
sslKey: undefined,
sslPass: undefined,
_readPreference: null,
socketOptions: [Object],
logger: [Object],
eventHandlers: [Object],
_serverState: 'connected',
_state: [Object],
recordQueryStats: false,
db: [Circular],
dbInstances: [Array],
connectionPool: [EventEmitter],
isMasterDoc: [Object] },
options:
{ read_preference_tags: null,
read_preference: 'primary',
native_parser: false,
readPreference: [ReadPreference],
safe: false,
w: 1 },
_applicationClosed: false,
native_parser: false,
bsonLib:
{ Code: [Function: Code],
Symbol: [Function: Symbol],
BSON: [Function],
DBRef: [Function: DBRef],
Binary: [Function],
ObjectID: [Function],
Long: [Function],
Timestamp: [Function],
Double: [Function: Double],
MinKey: [Function: MinKey],
MaxKey: [Function: MaxKey] },
bson: BSON {},
bson_deserializer:
{ Code: [Function: Code],
Symbol: [Function: Symbol],
BSON: [Function],
DBRef: [Function: DBRef],
Binary: [Function],
ObjectID: [Function],
Long: [Function],
Timestamp: [Function],
Double: [Function: Double],
MinKey: [Function: MinKey],
MaxKey: [Function: MaxKey] },
bson_serializer:
{ Code: [Function: Code],
Symbol: [Function: Symbol],
BSON: [Function],
DBRef: [Function: DBRef],
Binary: [Function],
ObjectID: [Function],
Long: [Function],
Timestamp: [Function],
Double: [Function: Double],
MinKey: [Function: MinKey],
MaxKey: [Function: MaxKey] },
_state: 'connected',
pkFactory:
{ [Function: ObjectID]
index: 0,
createPk: [Function: createPk],
createFromTime: [Function: createFromTime],
createFromHexString: [Function: createFromHexString] },
forceServerObjectId: false,
safe: false,
notReplied: {},
isInitializing: true,
auths: [],
openCalled: true,
commands: [],
logger:
{ error: [Function: error],
log: [Function: log],
debug: [Function: debug] },
slaveOk: false,
tag: 1554299599878,
eventHandlers:
{ error: [],
parseError: [],
poolReady: [],
message: [],
close: [] },
serializeFunctions: false,
raw: false,
recordQueryStats: false,
retryMiliSeconds: 1000,
numberOfRetries: 60,
readPreference:
ReadPreference { _type: 'ReadPreference', mode: 'primary', tags: undefined } },
collection:
Collection {
db:
Db {
_events: [Object: null prototype] {},
_eventsCount: 0,
_maxListeners: undefined,
databaseName: 'DB_A',
serverConfig: [Server],
options: [Object],
_applicationClosed: false,
native_parser: false,
bsonLib: [Object],
bson: BSON {},
bson_deserializer: [Object],
bson_serializer: [Object],
_state: 'connected',
pkFactory: [Function],
forceServerObjectId: false,
safe: false,
notReplied: {},
isInitializing: true,
auths: [],
openCalled: true,
commands: [],
logger: [Object],
slaveOk: false,
tag: 1554299599878,
eventHandlers: [Object],
serializeFunctions: false,
raw: false,
recordQueryStats: false,
retryMiliSeconds: 1000,
numberOfRetries: 60,
readPreference: [ReadPreference] },
collectionName: 'COL_A',
internalHint: null,
opts: {},
slaveOk: false,
serializeFunctions: false,
raw: false,
readPreference: 'primary',
pkFactory:
{ [Function: ObjectID]
index: 0,
createPk: [Function: createPk],
createFromTime: [Function: createFromTime],
createFromHexString: [Function: createFromHexString] } },
selector: {},
fields: undefined,
skipValue: 0,
limitValue: 0,
sortValue: undefined,
hint: null,
explainValue: undefined,
snapshot: undefined,
timeout: true,
tailable: undefined,
awaitdata: undefined,
numberOfRetries: 5,
currentNumberOfRetries: 5,
batchSizeValue: 0,
slaveOk: false,
raw: false,
read: 'primary',
returnKey: undefined,
maxScan: undefined,
min: undefined,
max: undefined,
showDiskLoc: undefined,
comment: undefined,
tailableRetryInterval: 100,
exhaust: false,
partial: false,
totalNumberOfRecords: 0,
items: [],
cursorId: Long { _bsontype: 'Long', low_: 0, high_: 0 },
dbName: undefined,
state: 0,
queryRun: false,
getMoreTimer: false,
collectionName: 'DB_A.COL_A' }
Here are some details on my setup:
mongod --version
db version v2.4.14
node --version
v10.15.3
NodeJS mongo driver -> 1.2.13
cat /etc/os-release
PRETTY_NAME="Raspbian GNU/Linux 9 (stretch)"
NAME="Raspbian GNU/Linux"
VERSION_ID="9"
VERSION="9 (stretch)"
ID=raspbian
ID_LIKE=debian
HOME_URL="http://www.raspbian.org/"
SUPPORT_URL="http://www.raspbian.org/RaspbianForums"
BUG_REPORT_URL="http://www.raspbian.org/RaspbianBugs"
cat /etc/debian_version
9.8
uname -a
Linux DietPi 4.14.98+ #1200 Tue Feb 12 20:11:02 GMT 2019 armv6l GNU/Linux
cat /proc/cpuinfo
processor : 0
model name : ARMv6-compatible processor rev 7 (v6l)
BogoMIPS : 697.95
Features : half thumb fastmult vfp edsp java tls
CPU implementer : 0x41
CPU architecture: 7
CPU variant : 0x0
CPU part : 0xb76
CPU revision : 7
Hardware : BCM2835
Revision : 000e
Serial : 00000000ce0ee037
Thank you.
if you want desire result you can get it using async await
MongoClient.connect(url, async (err, db) => {
if (err) {
console.log(err);
} else {
console.log("Connected to db");
var cursor = await db.collection("comments").find().toArray();
console.log({ cursor });
db.close();
}
});
But if you want to use cursor type with each method of cursor not sure why not working
also change mongodb version "^3.2.2" to "^2.2.33" no luck

Trouble getting a response from cursor.toArray() in Mongo/Node

node 0.10.24 + mongo node driver 1.3.23 on 32 bit linux
My callback here is never getting executed.
console.log(record_collection);
record_collection.find({}, function (error, cursor) {
console.log("record_collection.find() returned");
if (error) {
console.log(error);
callback(error);
}
else {
console.log("calling toArray with cursor");
cursor.toArray(function(error, docs){
console.log("cursor.toArray() returned");
if (error) {
console.log(error);
callback(error);
}
else {
callback(null, docs);
}
});
}
});
The output from this section goes like this:
{ db:
{ domain: null,
_events: {},
_maxListeners: 10,
databaseName: 'dbname',
serverConfig:
{ domain: null,
_events: {},
_maxListeners: 10,
_callBackStore: [Object],
_commandsStore: [Object],
auth: [Object],
_dbStore: [Object],
host: 'localhost',
port: 27017,
options: [Object],
internalMaster: false,
connected: false,
poolSize: 5,
disableDriverBSONSizeCheck: false,
_used: true,
replicasetInstance: null,
emitOpen: true,
ssl: false,
sslValidate: false,
sslCA: null,
sslCert: undefined,
sslKey: undefined,
sslPass: undefined,
serverCapabilities: null,
name: 'localhost:27017',
_readPreference: null,
socketOptions: [Object],
logger: [Object],
eventHandlers: [Object],
_serverState: 'connecting',
_state: [Object],
recordQueryStats: false,
socketTimeoutMS: [Getter/Setter],
db: [Circular],
dbInstances: [Object],
connectionPool: [Object] },
options: {},
_applicationClosed: false,
slaveOk: false,
bufferMaxEntries: -1,
native_parser: undefined,
bsonLib:
{ Code: [Function: Code],
Symbol: [Function: Symbol],
BSON: [Object],
DBRef: [Function: DBRef],
Binary: [Object],
ObjectID: [Object],
Long: [Object],
Timestamp: [Object],
Double: [Function: Double],
MinKey: [Function: MinKey],
MaxKey: [Function: MaxKey],
promoteLongs: true },
bson: { promoteLongs: true },
bson_deserializer:
{ Code: [Function: Code],
Symbol: [Function: Symbol],
BSON: [Object],
DBRef: [Function: DBRef],
Binary: [Object],
ObjectID: [Object],
Long: [Object],
Timestamp: [Object],
Double: [Function: Double],
MinKey: [Function: MinKey],
MaxKey: [Function: MaxKey],
promoteLongs: true },
bson_serializer:
{ Code: [Function: Code],
Symbol: [Function: Symbol],
BSON: [Object],
DBRef: [Function: DBRef],
Binary: [Object],
ObjectID: [Object],
Long: [Object],
Timestamp: [Object],
Double: [Function: Double],
MinKey: [Function: MinKey],
MaxKey: [Function: MaxKey],
promoteLongs: true },
_state: 'connecting',
pkFactory:
{ [Function: ObjectID]
index: 14382708,
createPk: [Function: createPk],
createFromTime: [Function: createFromTime],
createFromHexString: [Function: createFromHexString] },
forceServerObjectId: false,
safe: false,
notReplied: {},
isInitializing: true,
openCalled: true,
commands: [],
logger: { error: [Function], log: [Function], debug: [Function] },
tag: 1390462362041,
eventHandlers:
{ error: [],
parseError: [],
poolReady: [],
message: [],
close: [] },
serializeFunctions: false,
raw: false,
recordQueryStats: false,
retryMiliSeconds: 1000,
numberOfRetries: 60,
readPreference: undefined },
collectionName: 'gis_stops',
internalHint: null,
opts: {},
slaveOk: false,
serializeFunctions: false,
raw: false,
readPreference: 'primary',
pkFactory:
{ [Function: ObjectID]
index: 14382708,
createPk: [Function: createPk],
createFromTime: [Function: createFromTime],
createFromHexString: [Function: createFromHexString] },
serverCapabilities: undefined }
record_collection.find() returned
calling toArray with cursor
It looks like the first console.log() of the collection doesn't finish. But the other traces appear. Why isn't the callback being executed? Why don't I see "cursor.toArray() returned"?
This stopped working when I moved to a new server. The old server was running node 0.10.13 and mongodb 1.2.13.
From the record_collection trace:
db.serverConfig.connected = false;
The database was not connected.

Resources