Retrieve a document query with Email firebase firestore - node.js

Code:
At line number 57 I created a route to get the data according to user's email.
But I'm unable to get the specific data that this user added to the database. The response I'm getting is looking like this. I'm stuck here although I followed the instruction that is provided in the firebase firestore documentation.
QuerySnapshot {
_firestore: Firestore {
_authCredentials: FirebaseAuthCredentialsProvider {
authProvider: [Provider],
currentUser: [User],
tokenCounter: 0,
forceRefresh: false,
auth: null,
tokenListener: [Function (anonymous)]
},
_appCheckCredentials: FirebaseAppCheckTokenProvider {
appCheckProvider: [Provider],
forceRefresh: false,
appCheck: null,
tokenListener: [Function (anonymous)]
},
type: 'firestore',
_persistenceKey: '[DEFAULT]',
_settings: FirestoreSettingsImpl {
host: 'firestore.googleapis.com',
ssl: true,
credentials: undefined,
ignoreUndefinedProperties: false,
cacheSizeBytes: 41943040,
experimentalForceLongPolling: false,
experimentalAutoDetectLongPolling: false,
useFetchStreams: true
},
_settingsFrozen: true,
_app: FirebaseAppImpl {
_isDeleted: false,
_options: [Object],
_config: [Object],
_name: '[DEFAULT]',
_automaticDataCollectionEnabled: false,
_container: [ComponentContainer]
},
_databaseId: DatabaseId { projectId: 'parlour-1bcf7', database: '(default)' },
_queue: AsyncQueueImpl {
tail: [Promise],
retryableOps: [],
_isShuttingDown: false,
delayedOperations: [Array],
failure: null,
operationInProgress: true,
skipNonRestrictedTasks: false,
timerIdsToSkip: [],
backoff: [ExponentialBackoff],
visibilityHandler: [Function (anonymous)]
},
_firestoreClient: FirestoreClient {
authCredentials: [FirebaseAuthCredentialsProvider],
appCheckCredentials: [FirebaseAppCheckTokenProvider],
asyncQueue: [AsyncQueueImpl],
databaseInfo: [DatabaseInfo],
user: [User],
clientId: 'Hoh8WrPk3BFhkBsirvQx',
authCredentialListener: [Function (anonymous)],
appCheckCredentialListener: [Function (anonymous)],
offlineComponents: [MemoryOfflineComponentProvider],
onlineComponents: [OnlineComponentProvider]
}
},
_userDataWriter: ExpUserDataWriter {
firestore: Firestore {
_authCredentials: [FirebaseAuthCredentialsProvider],
_appCheckCredentials: [FirebaseAppCheckTokenProvider],
type: 'firestore',
_persistenceKey: '[DEFAULT]',
_settings: [FirestoreSettingsImpl],
_settingsFrozen: true,
_app: [FirebaseAppImpl],
_databaseId: [DatabaseId],
_queue: [AsyncQueueImpl],
_firestoreClient: [FirestoreClient]
}
},
_snapshot: ViewSnapshot {
query: QueryImpl {
path: [ResourcePath],
collectionGroup: null,
explicitOrderBy: [],
filters: [Array],
limit: null,
limitType: 'F',
startAt: null,
endAt: null,
memoizedOrderBy: [Array],
memoizedTarget: [TargetImpl]
},
docs: DocumentSet {
comparator: [Function (anonymous)],
keyedMap: [SortedMap],
sortedSet: [SortedMap]
},
oldDocs: DocumentSet {
comparator: [Function (anonymous)],
keyedMap: [SortedMap],
sortedSet: [SortedMap]
},
docChanges: [],
mutatedKeys: SortedSet { comparator: [Function: comparator], data: [SortedMap] },
fromCache: false,
syncStateChanged: true,
excludesMetadataChanges: false
},
metadata: SnapshotMetadata { hasPendingWrites: false, fromCache: false },
query: Query {
converter: null,
_query: QueryImpl {
path: [ResourcePath],
collectionGroup: null,
explicitOrderBy: [],
filters: [Array],
limit: null,
limitType: 'F',
startAt: null,
endAt: null,
memoizedOrderBy: [Array],
memoizedTarget: [TargetImpl]
},
type: 'query',
firestore: Firestore {
_authCredentials: [FirebaseAuthCredentialsProvider],
_appCheckCredentials: [FirebaseAppCheckTokenProvider],
type: 'firestore',
_persistenceKey: '[DEFAULT]',
_settings: [FirestoreSettingsImpl],
_settingsFrozen: true,
_app: [FirebaseAppImpl],
_databaseId: [DatabaseId],
_queue: [AsyncQueueImpl],
_firestoreClient: [FirestoreClient]
}
}
}

Replace lines 64 to 67 with the following snippet
for (const doc of querySnapshot.docs) {
console.log(doc.id, '=>', doc.data())
}

Related

Sum MongoDB column using aggregate - result has no property for the sum

I'm fairly new to MongoDB and Node and I came upon a problem developing a REST API.
The problem comes with the "Aggregate" function not properly returning results. After receiving the HTTP instruction, my API goes to run the specified command, the function that I'm using for this is:
const getDataAsync = async function getDataAsync(data) {
if (enabled !== true) { return {type: "Error", message: "Database not connected"}}
const operand = data.operand;
delete data.operand;
if (operand === "sum"){
clientHandler.collection("Sales2").aggregate([
{"_id": null, "total": {$sum: "Sale Gross Value"}}],
function (err, result) {console.log(result)});
}
}
But "result", gives out some weird data without the property "total". So far, based on other answers, I have tried:
Trying to read result[0] (Returns undefined)
Switching to (...).ToArray() instead of a second argument callback function.
Also, something important to note is that I replaced this line for a findOne (just to check that it is accessing the DB at this point) and returns OK.
Any help is appreciated, I'll dump all the output of log(result) in case someone knows how to interpret it.
PD: I know my code is crappy for an API because it is deeply hardcoded, it's just that I want it to work for this specific case before I try to open it up for a more parametric approach
EDIT: Answering some of the question comments:
I'm using _id: null because I saw it on a tutorial, I tried the query on mongo shell and it works.
I'll add some sample document at the end.
console.log(results):
AggregationCursor {
_readableState: ReadableState {
objectMode: true,
highWaterMark: 16,
buffer: BufferList { head: null, tail: null, length: 0 },
length: 0,
pipes: [],
flowing: null,
ended: false,
endEmitted: false,
reading: false,
sync: true,
needReadable: false,
emittedReadable: false,
readableListening: false,
resumeScheduled: false,
errorEmitted: false,
emitClose: true,
autoDestroy: true,
destroyed: false,
errored: null,
closed: false,
closeEmitted: false,
defaultEncoding: 'utf8',
awaitDrainWriters: null,
multiAwaitDrain: false,
readingMore: false,
decoder: null,
encoding: null,
[Symbol(kPaused)]: null
},
_events: [Object: null prototype] {},
_eventsCount: 0,
_maxListeners: undefined,
operation: AggregateOperation {
options: { readPreference: [ReadPreference] },
ns: MongoDBNamespace { db: 'Sales', collection: '$cmd' },
readPreference: ReadPreference {
mode: 'primary',
tags: undefined,
hedge: undefined
},
readConcern: undefined,
writeConcern: WriteConcern { w: 'majority' },
explain: false,
fullResponse: true,
target: 'Sales2',
pipeline: [ [Object] ],
hasWriteStage: false,
cursorState: {
cursorId: null,
cmd: {},
documents: [],
cursorIndex: 0,
dead: false,
killed: false,
init: false,
notified: false,
limit: 0,
skip: 0,
batchSize: 1000,
currentLimit: 0,
transforms: undefined,
raw: undefined,
reconnect: true
}
},
pool: null,
server: null,
disconnectHandler: undefined,
bson: undefined,
ns: 'Sales.$cmd',
namespace: MongoDBNamespace { db: 'Sales', collection: '$cmd' },
cmd: {},
options: {
readPreference: ReadPreference {
mode: 'primary',
tags: undefined,
hedge: undefined
}
},
topology: Server {
_events: [Object: null prototype] {
commandStarted: [Function (anonymous)],
commandSucceeded: [Function (anonymous)],
commandFailed: [Function (anonymous)],
serverOpening: [Function (anonymous)],
serverClosed: [Function (anonymous)],
serverDescriptionChanged: [Function (anonymous)],
serverHeartbeatStarted: [Function (anonymous)],
serverHeartbeatSucceeded: [Function (anonymous)],
serverHeartbeatFailed: [Function (anonymous)],
topologyOpening: [Function (anonymous)],
topologyClosed: [Function (anonymous)],
topologyDescriptionChanged: [Function (anonymous)],
joined: [Function (anonymous)],
left: [Function (anonymous)],
ping: [Function (anonymous)],
ha: [Function (anonymous)],
connectionPoolCreated: [Function (anonymous)],
connectionPoolClosed: [Function (anonymous)],
connectionCreated: [Function (anonymous)],
connectionReady: [Function (anonymous)],
connectionClosed: [Function (anonymous)],
connectionCheckOutStarted: [Function (anonymous)],
connectionCheckOutFailed: [Function (anonymous)],
connectionCheckedOut: [Function (anonymous)],
connectionCheckedIn: [Function (anonymous)],
connectionPoolCleared: [Function (anonymous)],
authenticated: [Function (anonymous)],
error: [Array],
timeout: [Array],
close: [Array],
parseError: [Array],
open: [Array],
fullsetup: [Array],
all: [Array],
reconnect: [Array]
},
_eventsCount: 35,
_maxListeners: Infinity,
s: {
coreTopology: [Server],
sCapabilities: null,
clonedOptions: [Object],
reconnect: true,
emitError: true,
poolSize: 20,
storeOptions: [Object],
store: [Store],
host: '127.0.0.1',
port: 27017,
options: [Object],
sessionPool: [ServerSessionPool],
sessions: Set(0) {},
promiseLibrary: [Function: Promise]
},
[Symbol(kCapture)]: false
},
cursorState: {
cursorId: null,
cmd: {},
documents: [],
cursorIndex: 0,
dead: false,
killed: false,
init: false,
notified: false,
limit: 0,
skip: 0,
batchSize: 1000,
currentLimit: 0,
transforms: undefined,
raw: undefined,
reconnect: true
},
logger: Logger { className: 'Cursor' },
s: {
numberOfRetries: 5,
tailableRetryInterval: 500,
currentNumberOfRetries: 5,
state: 0,
promiseLibrary: [Function: Promise],
explicitlyIgnoreSession: false
},
[Symbol(kCapture)]: false
}
Sample document:
{
"_id": {
"$oid": "5f88525a475fc997297fb93f"
},
"Date": {
"$date": "2018-01-01T00:01:00.000Z"
},
"Code": "54",
"Category": "ART._HYGIENIC",
"Name": "BELLA PODPASKI NOVA MAXI 10",
"Quantity": {
"$numberDecimal": "1"
},
"Unit Net Cost": {
"$numberDecimal": "2.66"
},
"Sale Net Cost": {
"$numberDecimal": "2.66"
},
"Unit Net Price": {
"$numberDecimal": "1.85"
},
"Sale Net Price": {
"$numberDecimal": "1.85"
},
"Unit Gross Value": {
"$numberDecimal": "2"
},
"Sale Gross Value": {
"$numberDecimal": "2"
},
"Share in Sales %": {
"$numberDecimal": "0"
},
"Margin %": {
"$numberDecimal": "-43.78"
},
"Unit Margin %": {
"$numberDecimal": "-0.81"
},
"Sell Margin %": {
"$numberDecimal": "-0.81"
},
"Share in Margin %": {
"$numberDecimal": "-0.01"
}
}
So I came up with this query.
db.collection.aggregate([
{
"$group": {
"_id": null,
"total": {
"$sum": "$Sale Gross Value"
}
}
}
])
I have created a mongo playground for this here.
https://mongoplayground.net/p/6nSiotXR960
Disclaimer :not an expert in nodejs :-P
Here is query in nodejs :
clientHandler.collection("Sales2").aggregate([
{'$group': {'_id':null, 'total':{'$sum': "$Sale Gross Value"}}}],
function (err, result) {console.log(result)});
Edit:-
Try this-
clientHandler.collection("Sales2").aggregate([
{'$group': {'_id':null, 'total':{'$sum': "$Sale Gross Value"}}}],
function (err, result) {result.forEach(doc => console.log(doc.total))});
OR this
var aggCursor = clientHandler.collection("Sales2").aggregate([
{'$group': {'_id':null, 'total':{'$sum': "$Sale Gross Value"}}}]);
await aggCursor.forEach(doc => console.log(doc.total))

How to read password protected PDF file in Nodejs and get it in buffer?

I tried using pdfjs-dist.
getting large json response.
var PDFJS=require('pdfjs-dist');
PDFJS.getDocument({ url: 'p1.pdf', password: '' }).then(function(pdf_doc)
{
console.log(pdf_doc);
}).catch(function(error) {
// incorrect password
// error is an object having 3 properties : name, message & code
});
Response
This is the whole response I am getting.
but I need response in buffer.
Can it be converted to buffer.
PDFDocumentProxy {
loadingTask:
{ _capability:
{ resolve: [Function], reject: [Function], promise: [Promise] },
_transport:
WorkerTransport {
messageHandler: [Object],
loadingTask: [Circular],
commonObjs: [Object],
fontLoader: [GenericFontLoader],
_params: [Object],
CMapReaderFactory: [DOMCMapReaderFactory],
destroyed: false,
destroyCapability: null,
_passwordCapability: null,
_networkStream: [PDFNodeStream],
_fullReader: [PDFNodeStreamFsFullReader],
_lastProgress: [Object],
pageCache: [],
pagePromises: [],
downloadInfoCapability: [Object],
numPages: 4,
pdfDocument: [Circular] },
_worker:
{ name: null,
destroyed: false,
postMessageTransfers: true,
verbosity: 1,
_readyCapability: [Object],
_port: [LoopbackPort],
_webWorker: null,
_messageHandler: [Object] },
docId: 'd0',
destroyed: false,
onPassword: null,
onProgress: null,
onUnsupportedFeature: null },
_pdfInfo:
{ numPages: 4,
fingerprint: '3432353738363537336c6e665361446f6f744f4a70' },
_transport:
WorkerTransport {
messageHandler:
{ sourceName: 'd0',
targetName: 'd0_worker',
comObj: [LoopbackPort],
callbackId: 1,
streamId: 1,
postMessageTransfers: true,
streamSinks: [Object],
streamControllers: [Object: null prototype] {},
callbacksCapabilities: [Object: null prototype] {},
actionHandler: [Object],
_onComObjOnMessage: [Function] },
loadingTask:
{ _capability: [Object],
_transport: [Circular],
_worker: [Object],
docId: 'd0',
destroyed: false,
onPassword: null,
onProgress: null,
onUnsupportedFeature: null },
commonObjs: { objs: [Object: null prototype] {} },
fontLoader:
GenericFontLoader {
docId: 'd0',
nativeFontFaces: [],
styleElement: null,
loadingContext: [Object],
loadTestFontId: 0 },
_params:
[Object: null prototype] {
url: 'p1.pdf',
password: '',
rangeChunkSize: 65536,
CMapReaderFactory: [Function: DOMCMapReaderFactory],
ignoreErrors: true,
pdfBug: false,
nativeImageDecoderSupport: 'none',
maxImageSize: -1,
isEvalSupported: true,
disableFontFace: true,
disableRange: false,
disableStream: false,
disableAutoFetch: false,
disableCreateObjectURL: false },
CMapReaderFactory: DOMCMapReaderFactory { baseUrl: null, isCompressed: false },
destroyed: false,
destroyCapability: null,
_passwordCapability: null,
_networkStream:
PDFNodeStream {
source: [Object],
url: [Url],
isHttp: false,
isFsUrl: true,
httpHeaders: {},
_fullRequest: [PDFNodeStreamFsFullReader],
_rangeRequestReaders: [Array] },
_fullReader:
PDFNodeStreamFsFullReader {
_url: [Url],
_done: false,
_storedError: null,
onProgress: [Function],
_contentLength: 112979,
_loaded: 112979,
_filename: null,
_disableRange: false,
_rangeChunkSize: 65536,
_isStreamingSupported: true,
_isRangeSupported: true,
_readableStream: [ReadStream],
_readCapability: [Object],
_headersCapability: [Object] },
_lastProgress: { loaded: 112979, total: 112979 },
pageCache: [],
pagePromises: [],
downloadInfoCapability:
{ resolve: [Function], reject: [Function], promise: [Promise] },
numPages: 4,
pdfDocument: [Circular] } }
*ignore below text*
efwrg rgsretg resgerstgh;ergh ;resjgysregh regjes powrjgu oiuueryoeq uieqroeqreqrilih ehr oiyeroeq ioiyeqroeq oieyqrioeq oieqyr oiyeqr oiyeqrp ioqyet oiehr oiyerh oieyreq oiyheqri iohereqk ioheqr qerioyqereq ioehqriheq rioqehriqeb ioeqrhpeq ioeqrhiqe ioqehriq ioqerhioq oirhqeipor oiqehrieq ioehqrq ioeqhrieq iohqerpq ieqhrpeq ioeqhrpeq iheqrpqe oiehrpqe ieqhrqierh ioeqhr ieqhr ioeqrh piqerh ieqhr iheqr piheqr ioheqr iheqr ioeqhrp ioqhre oieqhr oeqiyr qoeiryf pouqer poqure pouqr pouqre[q poquerq poqeur[q poqeur poqwuer poquer[ poqwur[wq poqr[ poqwhr powrq pow
You may open and read a password protected PDF like below. Working with your existing code:
var PDFJS = require('pdfjs-dist');
PDFJS.getDocument({ url: 'p1.pdf', password: '' }).then(function(pdf)
{
let text = [];
for(let i = 1; i <= pdf.numPages; i++) {
pdf.getPage(i).then(function(page) {
page.getTextContent().then(function(data) {
for(let j = 0; j < data.items.length; j++) {
text.push(data.items[j].str);
}
});
});
}
}).catch(function(error) {
// incorrect password
// error is an object having 3 properties : name, message & code
});

Mautic API cannot create DynamicContent

I am struggling to successfully execute create calls on the mautic REST api. In my node project I am using a standard express installation and a wrapper for the node api https://github.com/sambarnes90/node-mautic
I have authenticated my machine with the api and can PULL data without problem. The problem is POSTing data to it.
The documentation for the targeted post request is here: https://developer.mautic.org/#create-dynamic-content
This is my route. It derives from the example in node-mautic which works fine, but putting something into mautic does not work for me:
router.get('/api', function(req, res, next) {
//check auth and create config object
mautic.auth.checkAuth(function(config) {
// if all worked
if (config.auth_object) {
var testbody = {
"name": "apitest2"
}
//create call
mautic.dynamiccontent.createDynamicContent(config, testbody, function(data) {
console.log(data);
return res.send(data);
});
//request call for id=3
/*mautic.dynamiccontent.getDynamicContent(config, 3, function(data) {
console.log(data);
return res.send(data);
});
});*/
}
});
});
I am getting this response from the API:
[ { code: 400,
message: 'name: A name is required.',
details: { name: [Array] } } ]
This is the GitHub project for this: https://github.com/raphaelurban/mautic-api-test
EDIT:
I also tried:
var testbody = new Array();
testbody['name'] = 'apitest2';
with the same result.
Here is the full POST request:
Request {
domain: null,
_events:
{ error: [Function: bound ],
complete: [Function: bound ],
pipe: [Function] },
_eventsCount: 3,
_maxListeners: undefined,
body: '{"name":"apitest2"}',
callback: [Function],
method: 'POST',
readable: true,
writable: true,
explicitMethod: true,
_qs:
Querystring {
request: [Circular],
lib: { formats: [Object], parse: [Function], stringify: [Function] },
useQuerystring: undefined,
parseOptions: {},
stringifyOptions: {} },
_auth:
Auth {
request: [Circular],
hasAuth: false,
sentAuth: false,
bearerToken: null,
user: null,
pass: null },
_oauth: OAuth { request: [Circular], params: null },
_multipart:
Multipart {
request: [Circular],
boundary: 'afa47f83-3327-4d67-982d-4db6daab8a39',
chunked: false,
body: null },
_redirect:
Redirect {
request: [Circular],
followRedirect: true,
followRedirects: true,
followAllRedirects: false,
followOriginalHttpMethod: false,
allowRedirect: [Function],
maxRedirects: 10,
redirects: [],
redirectsFollowed: 0,
removeRefererHeader: false },
_tunnel:
Tunnel {
request: [Circular],
proxyHeaderWhiteList:
[ 'accept',
'accept-charset',
'accept-encoding',
'accept-language',
'accept-ranges',
'cache-control',
'content-encoding',
'content-language',
'content-location',
'content-md5',
'content-range',
'content-type',
'connection',
'date',
'expect',
'max-forwards',
'pragma',
'referer',
'te',
'user-agent',
'via' ],
proxyHeaderExclusiveList: [] },
headers: { host: 'hrutest.mautic.net', 'content-length': 19 },
setHeader: [Function],
hasHeader: [Function],
getHeader: [Function],
removeHeader: [Function],
localAddress: undefined,
pool: {},
dests: [],
__isRequestRequest: true,
_callback: [Function],
uri:
Url {
protocol: 'https:',
slashes: true,
auth: null,
host: 'hrutest.mautic.net',
port: 443,
hostname: 'hrutest.mautic.net',
hash: null,
search: '?access_token=ZTJlOWY3MzI0YTg4OWViNzU3YjY5YjFiZjRlOTU1OWFiYWM1N2ZmOTQ4OWI4NGI2NzZjZGUyMDg3ZWMxZmU5OA',
query: 'access_token=ZTJlOWY3MzI0YTg4OWViNzU3YjY5YjFiZjRlOTU1OWFiYWM1N2ZmOTQ4OWI4NGI2NzZjZGUyMDg3ZWMxZmU5OA',
pathname: '/api/dynamiccontents/new',
path: '/api/dynamiccontents/new?access_token=ZTJlOWY3MzI0YTg4OWViNzU3YjY5YjFiZjRlOTU1OWFiYWM1N2ZmOTQ4OWI4NGI2NzZjZGUyMDg3ZWMxZmU5OA',
href: 'https://hrutest.mautic.net/api/dynamiccontents/new?access_token=ZTJlOWY3MzI0YTg4OWViNzU3YjY5YjFiZjRlOTU1OWFiYWM1N2ZmOTQ4OWI4NGI2NzZjZGUyMDg3ZWMxZmU5OA' },
proxy: null,
tunnel: true,
setHost: true,
originalCookieHeader: undefined,
_disableCookies: true,
_jar: undefined,
port: 443,
host: 'hrutest.mautic.net',
path: '/api/dynamiccontents/new?access_token=ZTJlOWY3MzI0YTg4OWViNzU3YjY5YjFiZjRlOTU1OWFiYWM1N2ZmOTQ4OWI4NGI2NzZjZGUyMDg3ZWMxZmU5OA',
httpModule:
{ Server: { [Function: Server] super_: [Object] },
createServer: [Function: createServer],
globalAgent:
Agent {
domain: null,
_events: [Object],
_eventsCount: 1,
_maxListeners: undefined,
defaultPort: 443,
protocol: 'https:',
options: [Object],
requests: {},
sockets: [Object],
freeSockets: {},
keepAliveMsecs: 1000,
keepAlive: false,
maxSockets: Infinity,
maxFreeSockets: 256,
maxCachedSessions: 100,
_sessionCache: [Object] },
Agent: { [Function: Agent] super_: [Object] },
request: [Function: request],
get: [Function: get] },
agentClass:
{ [Function: Agent]
super_: { [Function: Agent] super_: [Object], defaultMaxSockets: Infinity } },
agent:
Agent {
domain: null,
_events: { free: [Function] },
_eventsCount: 1,
_maxListeners: undefined,
defaultPort: 443,
protocol: 'https:',
options: { path: null },
requests: {},
sockets: { 'hrutest.mautic.net:443:::::::::': [Array] },
freeSockets: {},
keepAliveMsecs: 1000,
keepAlive: false,
maxSockets: Infinity,
maxFreeSockets: 256,
maxCachedSessions: 100,
_sessionCache: { map: [Object], list: [Array] } } }
I haven't had much chance to test any more of this wrapper in recent months.
I would try sending it as an array though if possible?
Try these two combinations of testbody:
var testbody = [
"name": "apitest2"
]
Or
var testbody = {[
"name": "apitest2"
]}
And see what results you get?
Can you possibly get full logs of the request?
Finally I worked it out. At least it is some solution, I am not sure if this also works with the current function.
I found that all other tutorials use form instead of body when posting data. Additionally, their objects do not get JSON.stringified.
So with my object:
var testbody = {
name: 'apitest99'
};
It works when I change the function in node-mautic:
createDynamicContent: function(config, queryParameters, callback) {
var url = config.api_endpoint + "/dynamiccontents/new?access_token=" + config.auth_object.access_token;
//queryParameters = JSON.stringify(queryParameters);**
request.post({
url: url,
form: queryParameters
}, function(err, res) {
if (err) {
callback(err);
} else {
var asset = JSON.parse(res.body);
callback(asset);
}
})
},
And I am getting the following response from the API:
{ dynamicContent:
{ isPublished: true,
dateAdded: '2018-07-13T09:37:07+00:00',
dateModified: null,
createdBy: 1,
createdByUser: 'Raphael',
modifiedBy: null,
modifiedByUser: null,
id: 10,
name: 'apitest99',
category: null,
publishUp: null,
publishDown: null,
sentCount: 0,
variantParent: null,
variantChildren: [],
content: null,
filters: [],
isCampaignBased: true,
slotName: '' } }

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);
}

Writing A Mongoose Plug In- plugin() a method?

I am interested in writing a mongoose plug in to make all fields required. I know there are other ways to do this, but I like the idea of writing my own plug in.
From docs http://mongoosejs.com/docs/plugins:
// game-schema.js
var lastMod = require('./lastMod');
var Game = new Schema({ ... });
Game.plugin(lastMod, { index: true });
but when I create a model from my schema and look at the properties, I don't see a plugin() method:
var mongoose = require('mongoose');
var CpuSchema = require("../schemas/cpu");
var Cpu = mongoose.model('Cpu', CpuSchema);
console.log(Cpu);
module.exports = Cpu;
one#demo ~/cloudimageshare-monitoring/project $ node /home/one/cloudimageshare-monitoring/project/app/data/models/cpu.js
{ [Function: model]
base:
{ connections: [ [Object] ],
plugins: [],
models: { Cpu: [Circular] },
modelSchemas: { Cpu: [Object] },
options: { pluralization: true } },
modelName: 'Cpu',
model: [Function: model],
db:
{ base:
{ connections: [Object],
plugins: [],
models: [Object],
modelSchemas: [Object],
options: [Object] },
collections: { cpus: [Object] },
models: {},
replica: false,
hosts: null,
host: null,
port: null,
user: null,
pass: null,
name: null,
options: null,
otherDbs: [],
_readyState: 0,
_closeCalled: false,
_hasOpened: false,
_listening: false },
discriminators: undefined,
schema:
{ paths:
{ timeStamp: [Object],
avaiable: [Object],
status: [Object],
metrics: [Object],
_id: [Object],
__v: [Object] },
subpaths: {},
virtuals: { id: [Object] },
nested: {},
inherits: {},
callQueue: [],
_indexes: [],
methods: {},
statics: {},
tree:
{ timeStamp: [Object],
avaiable: [Function: Boolean],
status: [Function: String],
metrics: [Object],
_id: [Object],
id: [Object],
__v: [Function: Number] },
_requiredpaths: undefined,
discriminatorMapping: undefined,
_indexedpaths: undefined,
options:
{ id: true,
noVirtualId: false,
_id: true,
noId: false,
read: null,
shardKey: null,
autoIndex: true,
minimize: true,
discriminatorKey: '__t',
versionKey: '__v',
capped: false,
bufferCommands: true,
strict: true,
pluralization: true },
_events: {} },
options: undefined,
collection:
{ collection: null,
opts: { bufferCommands: true, capped: false },
name: 'cpus',
conn:
{ base: [Object],
collections: [Object],
models: {},
replica: false,
hosts: null,
host: null,
port: null,
user: null,
pass: null,
name: null,
options: null,
otherDbs: [],
_readyState: 0,
_closeCalled: false,
_hasOpened: false,
_listening: false },
queue: [ [Object] ],
buffer: true } }
Here on the model, I don't see a plugin() method.
The plugin method is defined on the Schema class and you can see it on your CpuSchema object.
On your Cpu model you can get it by calling
console.log(Cpu.schema.plugin)
From the mongoose source code on GitHub:
/**
* Registers a plugin for this schema.
*
* #param {Function} plugin callback
* #param {Object} opts
* #see plugins
* #api public
*/
Schema.prototype.plugin = function (fn, opts) {
fn(this, opts);
return this;
};
When you pass your plugin function to it it simply executes the function and passes the schema reference into it.

Resources