How to use data after Knex select query - node.js

I am having a little trouble with retrieving the data from a table using knex select.
I would like to do something like this
function getUserData(userId){
let user = knex.select('xp','money','rolls','twenty').from('users').where('user_id', userId);
return user;
}
user = getUserData(userId);
user.xp; // do something with this value
but this outputs the following (if i console.log it), but not the requested info from the Select query, unless i am just not sure how to retrieve it:
Builder {
client:
Client_MySQL {
config: { client: 'mysql', connection: [Object] },
connectionSettings:
{ host: '127.0.0.1',
user: 'XXXXXXXXXX',
password: 'XXXXXXXXXX',
database: 'XXXXXXXXXX' },
driver:
{ createConnection: [Function: createConnection],
createPool: [Function: createPool],
createPoolCluster: [Function: createPoolCluster],
createQuery: [Function: createQuery],
escape: [Function: escape],
escapeId: [Function: escapeId],
format: [Function: format],
raw: [Function: raw] },
pool:
Pool {
creator: [Function: create],
destroyer: [Function: destroy],
validate: [Function: validate],
log: [Function],
acquireTimeoutMillis: 60000,
createTimeoutMillis: 30000,
idleTimeoutMillis: 30000,
reapIntervalMillis: 1000,
createRetryIntervalMillis: 200,
propagateCreateError: true,
min: 2,
max: 10,
used: [],
free: [],
pendingCreates: [],
pendingAcquires: [],
destroyed: false,
interval: null },
valueForUndefined:
Raw {
client: [Circular],
sql: 'DEFAULT',
bindings: undefined,
_wrappedBefore: undefined,
_wrappedAfter: undefined,
_debug: undefined },
_events:
{ start: [Function],
query: [Function],
'query-error': [Function],
'query-response': [Function] },
_eventsCount: 4,
makeKnex: [Function: makeKnex] },
and: [Circular],
_single: { table: 'users', only: false },
_statements:
[ { grouping: 'columns', value: [Array] },
{ grouping: 'where',
type: 'whereBasic',
column: 'user_id',
operator: '=',
value: '341007826375802900',
not: false,
bool: 'and' } ],
_method: 'select',
_debug: undefined,
_joinFlag: 'inner',
_boolFlag: 'and',
_notFlag: false }
I'll write some more words here, as it requires me to do so, since it is mostly code. I hope this will be enough words.

The query run asynchronous, so you need to explicitly wait for it to finish. One way to do this is using promises:
knex.select('xp','money','rolls','twenty').from('users').where('user_id', userId)
.then(data => console.log(data));
Also make sure that the connection with the database is already established.

After config database just called an async function it will worked
const knex = require('knex')({
client: 'sqlite3',
connection: {
filename: './mydb.db',
},
useNullAsDefault: true
});
(async function(){
const posts = await knex('data');
console.log(posts)
})()
In this code i am using this sql query
SELECT * FROM data

Related

How do I retrieve only the raw data stored on my mongo database?

Here is the object that I am posting to mongoDb and that is visible in Mongo Compass
name: "Angular Course",
author: "Mosh",
tags: ["angular", "frontend"],
isPublished: true,
});
When I successfully post it with the .save() method. the returning object is a lot more complex.
I also receive the data the same way when I try to fetch the database.
'$__': InternalCache {
strictMode: true,
selected: undefined,
shardval: undefined,
saveError: undefined,
validationError: undefined,
adhocPaths: undefined,
removing: undefined,
inserting: true,
version: undefined,
getters: {},
_id: 60ee787103000551d4f4fc6c,
populate: undefined,
populated: undefined,
wasPopulated: false,
scope: undefined,
activePaths: StateMachine {
paths: {},
states: [Object],
stateNames: [Array],
forEach: [Function],
map: [Function]
},
pathsToScopes: {},
ownerDocument: undefined,
fullPath: undefined,
emitter: EventEmitter {
_events: [Object: null prototype] {},
_eventsCount: 0,
_maxListeners: 0,
[Symbol(kCapture)]: false
},
'$options': true
},
isNew: false,
errors: undefined,
_doc: {
tags: [
'angular',
'frontend',
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: 'tags',
isMongooseArray: true,
validators: [],
_schema: [SchemaArray]
],
date: 2021-07-14T05:38:57.964Z,
_id: 60ee787103000551d4f4fc6c,
name: 'Angular Course',
author: 'Mosh',
isPublished: true,
}
I want it to return only the object with parameters of the class. Is there a way i can do this in a simpler way? Any assistance would be greatly appreciated!
Here is the code that i used to create a new database object
.connect("mongodb://localhost:27017/playground")
.then(() => console.log("connected to mongodb"))
.catch((err) => console.error("couldnt not connect to mongodb:", err));
//this schema defines the shape of course documents on our Mongodb database
const courseSchema = new mongoose.Schema({
name: String,
author: String,
tags: [String],
date: { type: Date, default: Date.now },
isPublished: Boolean,
});
// compile the schema into a model to create a class
//model method takes 2 arguments
//singular name of the collection that this model is for
//schema that defines the shape of documents in this collection
//this returns a class and the class is named with Pascal naming convention
const Course = mongoose.model("Course", courseSchema);
//any asyncronous functionality must be run inside an async function
async function createCourse() {
// creating an object based on that class
const course = new Course({
name: "Angular Course",
author: "Mosh",
tags: ["angular", "frontend"],
isPublished: true,
});
// this method is an asyncronous method
const result = await course.save();
console.log(result);
The courses that are returned as the object from above
When you call new Course you create a mongoose model, which is also returned after you call course.save, in order to get only the data try using toObject method of Course model
// creating an object based on that class
const course = new Course({
name: "Angular Course",
author: "Mosh",
tags: ["angular", "frontend"],
isPublished: true,
});
// this method is an asyncronous method
const result = await course.save();
console.log(result.toObject());

Mongoose/MongoDB won't connect from Node.js

So i'm new to MongoDB/Mongoose, I am following many different tutorials online about how to connect my node.js server to mongodb using mongoose, however none of them seem to mention the issue i'm having. I have mongo server running on my machine, I can manipulate it find from the command line, but when connecting from node i run into a few problems. Mainly, its that It still says waiting for connections on Port 27017 but the connection is never made, the db I define in mongoose is never created, but also, I don't get any errors.
I do get some deprecation warnings regarding both body-parser and URL string parser. Not sure what to do about that. But also, i'm trying to log either a connection confirmation or an error if it can't connect. Instead it just logs a monster mongoose(?) object. See below
body-parser deprecated bodyParser: use individual json/urlencoded middlewares server.js:15:9 body-parser deprecated undefined extended: provide extended option node_modules\body-parser\index.js:105:29 (node:12152) DeprecationWarning: current URL string parser is deprecated, and will be removed in a future version. To use the new parser, pass option { useNewUrlParser: true } to MongoClient.connect. connected to [object Promise] + NativeConnection { base: Mongoose { connections: [ [Circular] ], models: { users: [Function] }, modelSchemas: { users: [Schema] }, options: { pluralization: true }, _pluralize: [Function: pluralize], Schema: { [Function: Schema] reserved: [Object], Types: [Object], ObjectId: [Function] }, model: [Function], plugins: [ [Array], [Array], [Array], [Array] ] }, collections: { users: NativeCollection { collection: [Collection], opts: [Object], name: 'users', collectionName: 'users', conn: [Circular], queue: [], buffer: false, emitter: [EventEmitter] } }, models: { users: { [Function: model] hooks: [Kareem], base: [Mongoose], modelName: 'users', model: [Function: model], db: [Circular], discriminators: undefined, events: [EventEmitter], '$appliedMethods': true, '$appliedHooks': true, _middleware: [Kareem], schema: [Schema], collection: [NativeCollection], Query: [Function], '$__insertMany': [Function], '$init': [Promise], '$caught': true, [Symbol(mongoose#Model)]: true } }, config: { autoIndex: true }, replica: false, options: null, otherDbs: [], relatedDbs: {}, states: [Object: null prototype] { '0': 'disconnected', '1': 'connected', '2': 'connecting', '3': 'disconnecting', '99': 'uninitialized', disconnected: 0, connected: 1, connecting: 2, disconnecting: 3, uninitialized: 99 }, _readyState: 1, _closeCalled: false, _hasOpened: true, '$internalEmitter': EventEmitter { _events: [Object: null prototype] { dropDatabase: [Function] }, _eventsCount: 1, _maxListeners: 0 }, _listening: false, _connectionOptions: { promiseLibrary: [Function: Promise], useNewUrlParser: false }, name: 'financeDB', host: 'localhost', port: 27017, user: undefined, pass: undefined, client: MongoClient { _events: [Object: null prototype] { left: [Function] }, _eventsCount: 1, _maxListeners: undefined, s: { url: 'mongodb://localhost:27017/financeDB', options: [Object], promiseLibrary: [Function: Promise], dbCache: [Object], sessions: [] }, topology: Server { _events: [Object], _eventsCount: 26, _maxListeners: Infinity, clientInfo: [Object], s: [Object] } }, '$initialConnection': Promise { <pending> }, db: Db { _events: [Object: null prototype] { reconnect: [Function], close: [Function], timeout: [Function] }, _eventsCount: 3, _maxListeners: undefined, s: { databaseName: 'financeDB', dbCache: {}, children: [], topology: [Server], options: [Object], logger: [Logger], bson: BSON {}, readPreference: [ReadPreference], bufferMaxEntries: -1, parentDb: null, pkFactory: undefined, nativeParser: undefined, promiseLibrary: [Function: Promise], noListener: false, readConcern: undefined }, serverConfig: [Getter], bufferMaxEntries: [Getter], databaseName: [Getter] } }
So why is this printing and what am I doing wrong re connection? Here is my server.js:
const express = require('express'),
path = require('path'),
bodyParser = require('body-parser'),
cors = require('cors'),
mongoose = require('mongoose');
config = require('.DB');
mongoose.Promise = global.Promise;
mongoose.connect(config.DB, { useNewUrlParser: true}).then(
()=> {console.log('Database is connected')},
err=>{console.log('Can not connect to the database' + err)}
);
const app = express();
let port = process.env.PORT || 4000;
const server = app.listen(function(){
console.log('Listening on port ' + port);
});
and my DB.js is just the uri
module.exports = {
DB: 'mongodb://localhost:27017/ng7crud'
};

Deploying Node-expressjs app in lambda - [Error: socket hang up] code: ECONNRESET

I am trying to deploy my Expressjs application into lambda, but i am getting below error. Please try to me to resolve this error.
lambda response:
{
"statusCode": 502,
"body": "",
"headers": {}
}
lambda log (it contains console of mongo connection and error)
NativeConnection {
base:
Mongoose {
connections: [ [Circular] ],
plugins: [],
models: { Student: [Object] },
modelSchemas: { Student: [Object] },
options: { pluralization: true } },
collections:
{ student:
NativeCollection {
collection: [Object],
opts: [Object],
name: 'student',
collectionName: 'student',
conn: [Circular],
queue: [],
buffer: false,
emitter: [Object] } },
models:
{ Student:
{ [Function: model]
hooks: [Object],
base: [Object],
modelName: 'Student',
model: [Function: model],
db: [Circular],
discriminators: undefined,
schema: [Object],
collection: [Object],
Query: [Object],
'$__insertMany': [Function],
insertMany: [Function] } },
config: { autoIndex: true },
replica: false,
hosts: null,
host: '1.0.0.0.0',
port: 3000,
user: undefined,
pass: undefined,
name: 'sudentdb',
options:
{ mongos: {},
db: { safe: true, forceServerObjectId: false },
auth: {},
server: { socketOptions: {}, auto_reconnect: true },
replset: { socketOptions: {} } },
otherDbs: [],
_readyState: 1,
_closeCalled: false,
_hasOpened: true,
_listening: false,
db:
EventEmitter {
domain: null,
_events:
{ close: [Function],
error: [Function],
reconnect: [Function],
timeout: [Function],
open: [Function],
parseError: [Function] },
_eventsCount: 6,
_maxListeners: undefined,
s:
{ databaseName: 'studentdb',
dbCache: {},
children: [],
topology: [Object],
options: [Object],
logger: [Object],
bson: {},
authSource: undefined,
readPreference: undefined,
bufferMaxEntries: -1,
parentDb: null,
pkFactory: undefined,
nativeParser: undefined,
promiseLibrary: [Function: Promise],
noListener: false,
readConcern: undefined },
serverConfig: [Getter],
bufferMaxEntries: [Getter],
databaseName: [Getter],
_listening: true },
_events:
{ connected: [Function],
error: [Function],
disconnected: [Function] },
_eventsCount: 3 }
{ [Error: socket hang up] code: 'ECONNRESET' }
student.model.js
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var studentSchema = new Schema({
name: String,
rollnumber: Number,
},{collection:"student"});
module.exports = mongoose.model('Student', studentSchema);
api/student(REST API - GET method)
exports.index = function(req, res) {
console.log(mongoose.connection)
Student.findOne({},function(err,doc){
if(err){
return res.json("error found");
}else{
return res.json(doc);
}
});
};
lambda.js
'use strict'
const awsServerlessExpress = require('aws-serverless-express');
const app = require('./bin/www');
const server = awsServerlessExpress.createServer(app);
exports.handler = (event,context)=>{
console.log("EVENT: " + JSON.stringify(event));
awsServerlessExpress.proxy(server,event,context);
}

Getting at all fields in the response to a monk findById call. nodejs/express/monk

Just cannot get my head around this after 10 hours of trying:
if I
users.findById(req.body.user_id,function(e,doc){});
and console.log the doc returned, all looks good:
{ _id: 54dcad6de4b01007caacb0cd,
username: 'realizertest',
password: '******************************',
first_name: 'Realizer',
second_name: 'Test',
display_name: 'Realizer Test',
email: 'system#realizerlabs.com' }
However, when trying to access the included fields, e.g. by:
user = users.findById(req.body.user_id,function(e,doc){});
var user_email = user.email;
I just get undefined. The user object looks like this:
{ col:
{ manager:
{ driver: [Object],
helper: [Object],
collections: [Object],
options: [Object],
_events: {} },
driver:
{ _construct_args: [],
_native: [Object],
_emitter: [Object],
_state: 2,
_connect_args: [Object] },
helper: { toObjectID: [Function], id: [Ob
name: 'users',
col:
{ _construct_args: [],
_native: [Object],
_emitter: [Object],
_state: 2,
_skin_db: [Object],
_collection_args: [Object],
id: [Object],
emitter: [Object] },
options: {} },
type: 'findOne',
opts: { fields: {}, safe: true },
domain: null,
_events:
{ error: [ [Function], [Function] ],
success: [ [Function], [Function] ] },
_maxListeners: 10,
emitted: {},
ended: false,
success: [Function],
error: [Function],
complete: [Function],
resolve: [Function],
fulfill: [Function],
reject: [Function],
query: { _id: 54dcad6de4b01007caacb0cd } }
I've also tried user.query.email but get the same result.
The findById obviously doesn't return a JSON object that I can use in this way.
How can I get at these fields?
It's an async call, so you need to use the callback, you can't assign that function to a variable:
users.findById(req.body.user_id,function(e,doc){
var user = doc;
console.log(user); //should see the object now, and access the props
});

Strange response when finding documents in MongoDB using Mongoose in Node.js

Thanks in advance for your help on this, it's much appreciated!
I'm using Node.js, MongoDB and Mongoose in a new project and I'm simply trying to find() the documents in a database. For brevity I'll just include the Mongoose code below (I'm not doing much more than this anyway right now):
var mongoose = require('mongoose');
mongoose.connect('mongodb://<username>:<password>#<sub-domain>.mongolab.com:<port>/<db>');
var schema = { email_address: String, invite: String }
, Users = mongoose.model('Users', new mongoose.Schema(schema));
console.log(Users.findOne({ 'email_address': 'jonathon#foo.bar' }, function(err, doc) { return doc; }));
I'm quite sure that should just echo the returned doc to the Node.js console (Terminal) but instead I'm getting this:
{ options: { populate: {} },
safe: undefined,
_conditions: { email_address: 'jonathon#foo.bar' },
_updateArg: {},
_fields: undefined,
op: 'findOne',
model:
{ [Function: model]
modelName: 'Users',
model: [Function: model],
options: undefined,
db:
{ base: [Object],
collections: [Object],
models: {},
replica: false,
hosts: null,
host: '<sub-domain>.mongolab.com',
port: <port>,
user: '<username>',
pass: '<password>',
name: '<db>',
options: [Object],
_readyState: 2,
_closeCalled: false,
_hasOpened: false,
db: [Object] },
schema:
{ paths: [Object],
subpaths: {},
virtuals: [Object],
nested: {},
inherits: {},
callQueue: [],
_indexes: [],
methods: {},
statics: {},
tree: [Object],
_requiredpaths: undefined,
options: [Object] },
collection:
{ collection: null,
name: 'users',
conn: [Object],
buffer: true,
queue: [Object],
opts: {} },
base:
{ connections: [Object],
plugins: [],
models: [Object],
modelSchemas: [Object],
options: {},
Collection: [Function: NativeCollection],
Connection: [Function: NativeConnection],
version: '3.5.4',
Mongoose: [Function: Mongoose],
Schema: [Object],
SchemaType: [Object],
SchemaTypes: [Object],
VirtualType: [Function: VirtualType],
Types: [Object],
Query: [Object],
Promise: [Function: Promise],
Model: [Object],
Document: [Object],
Error: [Object],
mongo: [Object] } } }
Obviously I've just obfuscated my real credential with the <username> bits, they are all correct in my code.
The database does have a document in it that would match the condition though even removing the condition from the findOne method yields no results!
I'm fairly new to Node.js so I you could explain your answers so I know for next time it'd be a great help! Thanks!
Change your code to:
Users.findOne({ 'email_address': 'jonathon#foo.bar' }, function(err, doc) {
console.log(doc);
});
I can't see from your code, but I think you are writing the value of the mongoose function to the console...
I totally forget, Node.js is asynchronous so the line console.log(Users.findOne({ 'email_address': 'jonathon#foo.bar' }, function(err, doc) { return doc; })); is indeed echoing to the console though no documents have been returned by the DB yet!
Instead the console.log method should be inside the find's callback, a la:
Users.find({}, function(err, doc) { console.log(doc); });

Resources