How to upload local image to facebook - facebook

I managed to upload an image to facebook using online URL but, when I try a local image using format file://path/to/imageI get the error
{"error":{"message":"(#100) url should represent a valid URL","type":"OAuthException","code":100}
is it doable ? or am doing it wrong ?
async function upload_fb_image(photo) {
return new Promise(resolve => {
FB.api(PAGE_ID + '/photos', 'post', {
message: 'Message',
url: LINK_TO_IMAGE,
published: false,
caption: 'Ad',
access_token: EXD_ACCESS_TOKEN
}).then(data => { resolve(data) })
})
}
as Form data
I tried as form data as mentioned in answers ... I receive ok response but, the image ID is not returned, I get the below JSON in reponse
Response {
size: 0,
timeout: 0,
[Symbol(Body internals)]:
{ body:
PassThrough {
_readableState:
ReadableState {
objectMode: false,
highWaterMark: 16384,
buffer: BufferList { head: [Object], tail: [Object], length: 1 },
length: 25,
pipes: null,
pipesCount: 0,
flowing: null,
ended: true,
endEmitted: false,
reading: false,
sync: false,
needReadable: false,
emittedReadable: false,
readableListening: false,
resumeScheduled: false,
paused: true,
emitClose: true,
autoDestroy: false,
destroyed: false,
defaultEncoding: 'utf8',
awaitDrain: 0,
readingMore: false,
decoder: null,
encoding: null },
readable: true,
_events:
[Object: null prototype] {
prefinish:
{ [Function: prefinish]
[length]: 0,
[name]: 'prefinish',
[prototype]: prefinish { [constructor]: [Circular] } },
error:
{ [Function]
[length]: 1,
[name]: '',
[prototype]: { [constructor]: [Circular] } } },
_eventsCount: 2,
_maxListeners: undefined,
_writableState:
WritableState {
objectMode: false,
highWaterMark: 16384,
finalCalled: false,
needDrain: false,
ending: true,
ended: true,
finished: true,
destroyed: false,
decodeStrings: true,
defaultEncoding: 'utf8',
length: 0,
writing: false,
corked: 0,
sync: false,
bufferProcessing: false,
onwrite:
{ [Function: bound onwrite] [length]: 1, [name]: 'bound onwrite' },
writecb: null,
writelen: 0,
bufferedRequest: null,
lastBufferedRequest: null,
pendingcb: 0,
prefinished: true,
errorEmitted: false,
emitClose: true,
autoDestroy: false,
bufferedRequestCount: 0,
corkedRequestsFree:
{ next: null,
entry: null,
finish:
{ [Function: bound onCorkedFinish] [length]: 1, [name]: 'bound onCorkedFinish' } } },
writable: false,
allowHalfOpen: true,
_transformState:
{ afterTransform:
{ [Function: bound afterTransform] [length]: 2, [name]: 'bound afterTransform' },
needTransform: false,
transforming: false,
writecb: null,
writechunk: null,
writeencoding: 'buffer' } },
disturbed: false,
error: null },
[Symbol(Response internals)]:
{ url: 'https://graph.facebook.com/page_id/photos',
status: 200,
statusText: 'OK',
headers:
Headers {
[Symbol(map)]:
[Object: null prototype] {
'x-business-use-case-usage':
[ '{"1006471116044666":[{"type":"pages","call_count":1,"total_cputime":1,"total_time":1,"estimated_time_to_regain_access":0}]}',
[length]: 1 ],
'content-type': [ 'application/json; charset=UTF-8', [length]: 1 ],
'facebook-api-version': [ 'v2.10', [length]: 1 ],
'strict-transport-security': [ 'max-age=15552000; preload', [length]: 1 ],
pragma: [ 'no-cache', [length]: 1 ],
'x-fb-rev': [ '1001316471', [length]: 1 ],
'access-control-allow-origin': [ '*', [length]: 1 ],
'cache-control':
[ 'private, no-cache, no-store, must-revalidate', [length]: 1 ],
'x-fb-trace-id': [ 'CSSaQru0iZZ', [length]: 1 ],
'x-fb-request-id': [ 'AguAWIpbfPySfVvwPjZZBec', [length]: 1 ],
expires: [ 'Sat, 01 Jan 2000 00:00:00 GMT', [length]: 1 ],
'x-fb-debug':
[ 'NnSTSun7s8VUcMnXu9cUYXQh/7laST0pILTNbAJrS0mtGHGXnQt17fRtyhS8R+RkZWyawJ4meKDWNKT1N+1uBA==',
[length]: 1 ],
date: [ 'Sat, 19 Oct 2019 01:31:32 GMT', [length]: 1 ],
'x-fb-trip-id': [ '1886706526', [length]: 1 ],
'alt-svc': [ 'h3-23=":443"; ma=3600', [length]: 1 ],
connection: [ 'close', [length]: 1 ],
'content-length': [ '25', [length]: 1 ] } },
counter: 0 } }

The url must be a public url, not some url from your local computer. Alternatively, you can use FormData:
const fileReader = new FileReader();
const file = document.getElementById('imageInput').files[0];
fileReader.onloadend = async () => {
const photoData = new Blob([fileReader.result], {type: 'image/jpg'});
const formData = new FormData();
formData.append('access_token', pageAccessToken);
formData.append('source', photoData);
formData.append('message', 'some status message');
let response = await fetch(`https://graph.facebook.com/${pageId}/photos`, {
body: formData,
method: 'post'
});
response = await response.json();
console.log(response);
};
fileReader.readAsArrayBuffer(file);
Source: https://www.devils-heaven.com/facebook-javascript-sdk-photo-upload-with-formdata/

finally it was solved using the below method
const formData = {
access_token: EXD_ACCESS_TOKEN,
source: fs.createReadStream("path/to/image"),
published: 'false'
}
console.log('sendning request')
request.post({ url: `https://graph.facebook.com/${PAGE_ID}/photos`, formData: formData }, function optionalCallback(err, httpResponse, body) {
if (err) {
return console.error('upload failed:', err);
}
resolve(body)
});

Related

Next.js + Apollo + Mongodb : Unable to have acces to Apollo context in SSR mode

i am triying to connect MongoDB with the NextJS API route Apollo example:
https://github.com/vercel/next.js/blob/canary/examples/api-routes-apollo-server-and-client
I cannot find any official doc. So i follow this topic:
Connect Apollo with mongodb
The idea is to connect Mongodb from the context of ApolloServer
pages/api/graphql.js
import { ApolloServer } from 'apollo-server-micro';
import { schema } from '../../apollo/schema';
import { connectToDatabase } from '../../utils/mongodb';
const apolloServer = new ApolloServer({
schema,
context: async () => {
const { db } = await connectToDatabase();
return { db };
},
});
export const config = {
api: {
bodyParser: false,
},
};
export default apolloServer.createHandler({ path: '/api/graphql' });
the "connectToDatabase" is coming from the example "with-mongo"
https://github.com/vercel/next.js/blob/canary/examples/with-mongodb/util/mongodb.js
There is 3 ways of rendering pages in NextJS. When i connect my db like so (inside the ApolloServer context) it works just fine with the client side rendering but not at all with the Static and Server Side Rendering. The context inside my resolver function is undefined.
apollo/resolvers.js
export const resolvers = {
Query: {
async getAllCards(_parent, _args, _context, _info) {
console.log('_context resolver :>> ', _context);
const res = await _context.db.db
.collection('cards')
.find({})
.limit(20)
.toArray();
console.log('res :>> ', res);
return res;
},
},
};
At that point i tried to follow this topic
Next.js graphql context is empty {} on SSR getServerSideProps
Following thoses steps i am ending with 2 files modified:
pages/api/graphql
import { ApolloServer } from 'apollo-server-micro';
import { schema } from '../../apollo/schema';
import { connectToDatabase } from '../../utils/mongodb';
async function contextResolver(ctx) {
ctx.db = await connectToDatabase();
return ctx;
}
const apolloServer = new ApolloServer({
schema,
context: contextResolver,
});
export const config = {
api: {
bodyParser: false,
},
};
export default apolloServer.createHandler({ path: '/api/graphql' });
and
pages/explore_SSR.js
import gql from 'graphql-tag';
import Link from 'next/link';
import { initializeApollo } from '../apollo/client';
import { connectToDatabase } from '../utils/mongodb';
const Explore = () => {
return (
// UI Stuff
)
}
export async function getServerSideProps(ctx) {
console.log('ctx :>> ', ctx);
async function contextResolver(ctx) {
ctx.db = await connectToDatabase();
return ctx;
}
await contextResolver(ctx);
console.log('ctx after :>> ', ctx);
const apolloClient = initializeApollo(null, ctx);
await apolloClient.query({
query: gql`
query GetAllMementoQuery {
getAllMemento {
title
}
}
`,
});
return {
props: {
props: { initialApolloState: apolloClient.cache.extract() },
},
};
}
export default Explore;
result of the console.log: console.log('ctx after :>> ', ctx);
ctx after :>> {
req: IncomingMessage {
_readableState: ReadableState {
objectMode: false,
highWaterMark: 16384,
buffer: BufferList { head: null, tail: null, length: 0 },
length: 0,
pipes: [],
flowing: null,
ended: true,
endEmitted: false,
reading: false,
sync: true,
needReadable: false,
emittedReadable: false,
readableListening: false,
resumeScheduled: false,
errorEmitted: false,
emitClose: true,
autoDestroy: false,
destroyed: false,
errored: null,
closed: false,
closeEmitted: false,
defaultEncoding: 'utf8',
awaitDrainWriters: null,
multiAwaitDrain: false,
readingMore: true,
decoder: null,
encoding: null,
[Symbol(kPaused)]: null
},
_events: [Object: null prototype] { end: [Function: clearRequestTimeout] },
_eventsCount: 1,
_maxListeners: undefined,
socket: Socket {
connecting: false,
_hadError: false,
_parent: null,
_host: null,
_readableState: [ReadableState],
_events: [Object: null prototype],
_eventsCount: 8,
_maxListeners: undefined,
_writableState: [WritableState],
allowHalfOpen: true,
_sockname: null,
_pendingData: null,
_pendingEncoding: '',
server: [Server],
_server: [Server],
parser: [HTTPParser],
on: [Function: socketListenerWrap],
addListener: [Function: socketListenerWrap],
prependListener: [Function: socketListenerWrap],
_paused: false,
_httpMessage: [ServerResponse],
timeout: 0,
[Symbol(async_id_symbol)]: 285916,
[Symbol(kHandle)]: [TCP],
[Symbol(kSetNoDelay)]: false,
[Symbol(lastWriteQueueSize)]: 0,
[Symbol(timeout)]: Timeout {
_idleTimeout: -1,
_idlePrev: null,
_idleNext: null,
_idleStart: 24100466,
_onTimeout: null,
_timerArgs: undefined,
_repeat: null,
_destroyed: true,
[Symbol(refed)]: false,
[Symbol(kHasPrimitive)]: false,
[Symbol(asyncId)]: 290206,
[Symbol(triggerId)]: 290203
},
[Symbol(kBuffer)]: null,
[Symbol(kBufferCb)]: null,
[Symbol(kBufferGen)]: null,
[Symbol(kCapture)]: false,
[Symbol(kBytesRead)]: 0,
[Symbol(kBytesWritten)]: 0,
[Symbol(RequestTimeout)]: undefined
},
httpVersionMajor: 1,
httpVersionMinor: 1,
httpVersion: '1.1',
complete: true,
headers: {
host: 'localhost:3000',
'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:88.0) Gecko/20100101 Firefox/88.0',
accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
'accept-language': 'fr,fr-FR;q=0.8,en-US;q=0.5,en;q=0.3',
'accept-encoding': 'gzip, deflate',
referer: 'http://localhost:3000/explore_clientSide',
dnt: '1',
connection: 'keep-alive',
'upgrade-insecure-requests': '1',
'sec-gpc': '1'
},
rawHeaders: [
'Host',
'localhost:3000',
'User-Agent',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:88.0) Gecko/20100101 Firefox/88.0',
'Accept',
'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
'Accept-Language',
'fr,fr-FR;q=0.8,en-US;q=0.5,en;q=0.3',
'Accept-Encoding',
'gzip, deflate',
'Referer',
'http://localhost:3000/explore_clientSide',
'DNT',
'1',
'Connection',
'keep-alive',
'Upgrade-Insecure-Requests',
'1',
'Sec-GPC',
'1'
],
trailers: {},
rawTrailers: [],
aborted: false,
upgrade: false,
url: '/explore_SSR',
method: 'GET',
statusCode: null,
statusMessage: null,
client: Socket {
connecting: false,
_hadError: false,
_parent: null,
_host: null,
_readableState: [ReadableState],
_events: [Object: null prototype],
_eventsCount: 8,
_maxListeners: undefined,
_writableState: [WritableState],
allowHalfOpen: true,
_sockname: null,
_pendingData: null,
_pendingEncoding: '',
server: [Server],
_server: [Server],
parser: [HTTPParser],
on: [Function: socketListenerWrap],
addListener: [Function: socketListenerWrap],
prependListener: [Function: socketListenerWrap],
_paused: false,
_httpMessage: [ServerResponse],
timeout: 0,
[Symbol(async_id_symbol)]: 285916,
[Symbol(kHandle)]: [TCP],
[Symbol(kSetNoDelay)]: false,
[Symbol(lastWriteQueueSize)]: 0,
[Symbol(timeout)]: Timeout {
_idleTimeout: -1,
_idlePrev: null,
_idleNext: null,
_idleStart: 24100466,
_onTimeout: null,
_timerArgs: undefined,
_repeat: null,
_destroyed: true,
[Symbol(refed)]: false,
[Symbol(kHasPrimitive)]: false,
[Symbol(asyncId)]: 290206,
[Symbol(triggerId)]: 290203
},
[Symbol(kBuffer)]: null,
[Symbol(kBufferCb)]: null,
[Symbol(kBufferGen)]: null,
[Symbol(kCapture)]: false,
[Symbol(kBytesRead)]: 0,
[Symbol(kBytesWritten)]: 0,
[Symbol(RequestTimeout)]: undefined
},
_consuming: false,
_dumped: false,
cookies: [Getter/Setter],
__NEXT_INIT_QUERY: {},
[Symbol(kCapture)]: false,
[Symbol(RequestTimeout)]: undefined
},
res: <ref *1> ServerResponse {
_events: [Object: null prototype] { finish: [Function: bound resOnFinish] },
_eventsCount: 1,
_maxListeners: undefined,
outputData: [],
outputSize: 0,
writable: true,
destroyed: false,
_last: false,
chunkedEncoding: false,
shouldKeepAlive: true,
_defaultKeepAlive: true,
useChunkedEncodingByDefault: true,
sendDate: true,
_removedConnection: false,
_removedContLen: false,
_removedTE: false,
_contentLength: null,
_hasBody: true,
_trailer: '',
finished: false,
_headerSent: false,
socket: Socket {
connecting: false,
_hadError: false,
_parent: null,
_host: null,
_readableState: [ReadableState],
_events: [Object: null prototype],
_eventsCount: 8,
_maxListeners: undefined,
_writableState: [WritableState],
allowHalfOpen: true,
_sockname: null,
_pendingData: null,
_pendingEncoding: '',
server: [Server],
_server: [Server],
parser: [HTTPParser],
on: [Function: socketListenerWrap],
addListener: [Function: socketListenerWrap],
prependListener: [Function: socketListenerWrap],
_paused: false,
_httpMessage: [Circular *1],
timeout: 0,
[Symbol(async_id_symbol)]: 285916,
[Symbol(kHandle)]: [TCP],
[Symbol(kSetNoDelay)]: false,
[Symbol(lastWriteQueueSize)]: 0,
[Symbol(timeout)]: Timeout {
_idleTimeout: -1,
_idlePrev: null,
_idleNext: null,
_idleStart: 24100466,
_onTimeout: null,
_timerArgs: undefined,
_repeat: null,
_destroyed: true,
[Symbol(refed)]: false,
[Symbol(kHasPrimitive)]: false,
[Symbol(asyncId)]: 290206,
[Symbol(triggerId)]: 290203
},
[Symbol(kBuffer)]: null,
[Symbol(kBufferCb)]: null,
[Symbol(kBufferGen)]: null,
[Symbol(kCapture)]: false,
[Symbol(kBytesRead)]: 0,
[Symbol(kBytesWritten)]: 0,
[Symbol(RequestTimeout)]: undefined
},
_header: null,
_keepAliveTimeout: 5000,
_onPendingData: [Function: bound updateOutgoingData],
_sent100: false,
_expect_continue: false,
statusCode: 200,
flush: [Function: flush],
write: [Function: write],
end: [Function: end],
on: [Function: on],
writeHead: [Function: writeHead],
[Symbol(kCapture)]: false,
[Symbol(kNeedDrain)]: false,
[Symbol(corked)]: 0,
[Symbol(kOutHeaders)]: null
},
query: {},
resolvedUrl: '/explore_SSR',
locales: undefined,
locale: undefined,
defaultLocale: undefined,
db: {
client: MongoClient {
_events: [Object: null prototype],
_eventsCount: 1,
_maxListeners: undefined,
s: [Object],
topology: [NativeTopology],
[Symbol(kCapture)]: false
},
db: Db {
_events: [Object: null prototype] {},
_eventsCount: 0,
_maxListeners: undefined,
s: [Object],
serverConfig: [Getter],
bufferMaxEntries: [Getter],
databaseName: [Getter],
[Symbol(kCapture)]: false
}
}
}
But it's not working for me. The _context of my resolver is still undefined.
(console.log in apollo/resolvers.js: _context :>> undefined)
Maybe we cannot use Apollo and Database connection with the API route and Server side rendering mode or i just missing something big.
Any idea of how i could implement the Mongodb database connection to have acces to it from my resolver in any kind of rendering mode?

Why is mongoDB aggregation $count method gives an object of AggregationCursor as result using node.js and promise?

I am trying to get count of an array in a document by using Mongodb aggregation $count operator.
I am using node.js and promise for this. Here is my code:
getDaysPresent:(id)=>{
return new Promise(async(resolve,reject)=>{
let days=await db.get().collection(collection.'student_collection').aggregate([
{
$match:{_id:ObjectId(id)}
},{
$unwind:"$attendance"
},{
$count:"attendance"
}
])
resolve(days)
})
}
When I try this Mongo Db code in Robo3T it gives the key and value object properly. But when code
executed the console of days gives a AggregationCursor objects with the below details:
AggregationCursor {
_readableState: ReadableState {
objectMode: true,
highWaterMark: 16,
buffer: BufferList { head: null, tail: null, length: 0 },
length: 0,
pipes: null,
pipesCount: 0,
flowing: null,
ended: false,
endEmitted: false,
reading: false,
sync: true,
needReadable: false,
emittedReadable: false,
readableListening: false,
resumeScheduled: false,
emitClose: true,
autoDestroy: false,
destroyed: false,
defaultEncoding: 'utf8',
awaitDrainWriters: null,
multiAwaitDrain: false,
readingMore: false,
decoder: null,
encoding: null,
[Symbol(kPaused)]: null
},
readable: true,
_events: [Object: null prototype] {},
_eventsCount: 0,
_maxListeners: undefined,
operation: AggregateOperation {
options: { readPreference: [ReadPreference] },
ns: MongoDBNamespace { db: 'classroom', collection: '$cmd' },
readPreference: ReadPreference {
mode: 'primary',
tags: undefined,
hedge: undefined
},
readConcern: undefined,
writeConcern: undefined,
explain: false,
fullResponse: true,
target: 'student',
pipeline: [ [Object], [Object], [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: 'classroom.$cmd',
namespace: MongoDBNamespace { db: 'classroom', collection: '$cmd' },
cmd: {},
options: {
readPreference: ReadPreference {
mode: 'primary',
tags: undefined,
hedge: undefined
}
},
topology: Server {
_events: [Object: null prototype] {
commandStarted: [Function],
commandSucceeded: [Function],
commandFailed: [Function],
serverOpening: [Function],
serverClosed: [Function],
serverDescriptionChanged: [Function],
serverHeartbeatStarted: [Function],
serverHeartbeatSucceeded: [Function],
serverHeartbeatFailed: [Function],
topologyOpening: [Function],
topologyClosed: [Function],
topologyDescriptionChanged: [Function],
joined: [Function],
left: [Function],
ping: [Function],
ha: [Function],
connectionPoolCreated: [Function],
connectionPoolClosed: [Function],
connectionCreated: [Function],
connectionReady: [Function],
connectionClosed: [Function],
connectionCheckOutStarted: [Function],
connectionCheckOutFailed: [Function],
connectionCheckedOut: [Function],
connectionCheckedIn: [Function],
connectionPoolCleared: [Function],
authenticated: [Function],
error: [Array],
timeout: [Array],
close: [Array],
parseError: [Array],
open: [Array],
fullsetup: [Array],
all: [Array],
reconnect: [Array]
},
_eventsCount: 35,
_maxListeners: Infinity,
s: {
coreTopology: [Server],
sCapabilities: [ServerCapabilities],
clonedOptions: [Object],
reconnect: true,
emitError: true,
poolSize: 5,
storeOptions: [Object],
store: [Store],
host: 'localhost',
port: 27017,
options: [Object],
sessionPool: [ServerSessionPool],
sessions: Set {},
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
}
My sample document as follow:
{
"_id" : ObjectId("5fd6fa3b4150e552f0b75935"),
"Name" : "Bobby",
"Gender" : "Male",
"RollNo" : "1",
"attendance" : [
"2/1/2021",
"3/1/2021",
"4/1/2021"
]
}
IF you guys know about this please let me know. And by the by this is my first question in stackoverflow so please give me suggestions to improve this question. Thank you
You could use $size operator to compute the length of an array field in the document. Please modify to suit the programming language and driver.
db.user.aggregate([
{
$project: {
length: {
$size: "$attendance"
}
}
}
])
https://mongoplayground.net/p/UbQh1feZaF0
I got the $count properly, when I add toArray() to the end of aggregation method. The count object will be in an array.
getPresentDays:(id)=>{
return new Promise(async(resolve,reject)=>{
var days=await db.get().collection(collection.STUDENT_COLLECTION).aggregate([
{
$match:{_id:ObjectId(id)}
},{
$unwind:"$attendance"
},{
$count:"attendance"
}
]).toArray()
resolve(days[0].attendance)
})
}

Do I need to connect to Mongo over and over again?

I am making a discord bot. When I was using java, I saved the data to mongo by creating different databases for each server my bot is in but on javascript I can only use one database.
And the only database it lets me connect/see is test database, other than that it shows everything as undefined.
And Mongo js docs tell me to connect to database over and over again but when using java I just connected on bot launch and was able to use it whenever I want. I tried all the examples I could find on stackoverflow but none of them helped me at all.
app.js :
require("./handler/mongo")();
client.on("ready", () => {
console.log(global.mongoclient.db("574612262275252231").collection("settings").find({}));
}
mongo.js:
const mongo = require('mongodb').MongoClient;
module.exports = function(){
mongo.connect(uri, (err, client) => {
if(err) throw err;
global.mongoclient = client;
console.log("a");
});
}
console output:
a
Cursor {
_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: false,
destroyed: false,
defaultEncoding: 'utf8',
awaitDrainWriters: null,
multiAwaitDrain: false,
readingMore: false,
decoder: null,
encoding: null,
[Symbol(kPaused)]: null
},
readable: true,
_events: [Object: null prototype] {},
_eventsCount: 0,
_maxListeners: undefined,
operation: FindOperation {
options: {
skip: 0,
limit: 0,
raw: undefined,
hint: null,
timeout: undefined,
slaveOk: true,
readPreference: [ReadPreference],
db: [Db],
promiseLibrary: [Function: Promise]
},
ns: MongoDBNamespace {
db: '574612262275252231',
collection: 'settings'
},
cmd: {
find: '574612262275252231.settings',
limit: 0,
skip: 0,
query: {},
raw: undefined,
hint: null,
timeout: undefined,
slaveOk: true,
readPreference: [ReadPreference]
},
readPreference: ReadPreference { mode: 'primary', tags: undefined },
cursorState: {
cursorId: null,
cmd: [Object],
documents: [],
cursorIndex: 0,
dead: false,
killed: false,
init: false,
notified: false,
limit: 0,
skip: 0,
batchSize: 1000,
currentLimit: 0,
transforms: undefined,
raw: undefined
}
},
pool: null,
server: null,
disconnectHandler: undefined,
bson: undefined,
ns: '574612262275252231.settings',
namespace: MongoDBNamespace { db: '574612262275252231', collection: 'settings' },
cmd: {
find: '574612262275252231.settings',
limit: 0,
skip: 0,
query: {},
raw: undefined,
hint: null,
timeout: undefined,
slaveOk: true,
readPreference: ReadPreference { mode: 'primary', tags: undefined }
},
options: {
skip: 0,
limit: 0,
raw: undefined,
hint: null,
timeout: undefined,
slaveOk: true,
readPreference: ReadPreference { mode: 'primary', tags: undefined },
db: Db {
_events: [Object: null prototype] {},
_eventsCount: 0,
_maxListeners: undefined,
s: [Object],
serverConfig: [Getter],
bufferMaxEntries: [Getter],
databaseName: [Getter],
[Symbol(kCapture)]: false
},
promiseLibrary: [Function: Promise]
},
topology: ReplSet {
_events: [Object: null prototype] {
authenticated: [Function (anonymous)],
error: [Array],
timeout: [Array],
close: [Array],
parseError: [Array],
reconnect: [Array],
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)],
open: [Function],
fullsetup: [Function],
all: [Function]
},
_eventsCount: 35,
_maxListeners: Infinity,
s: {
coreTopology: [ReplSet],
sCapabilities: [ServerCapabilities],
tag: undefined,
storeOptions: [Object],
clonedOptions: [Object],
store: [Store],
options: [Object],
sessionPool: [ServerSessionPool],
sessions: Set(0) {},
promiseLibrary: [Function: Promise]
},
[Symbol(kCapture)]: false
},
cursorState: {
cursorId: null,
cmd: {
find: '574612262275252231.settings',
limit: 0,
skip: 0,
query: {},
raw: undefined,
hint: null,
timeout: undefined,
slaveOk: true,
readPreference: [ReadPreference]
},
documents: [],
cursorIndex: 0,
dead: false,
killed: false,
init: false,
notified: false,
limit: 0,
skip: 0,
batchSize: 1000,
currentLimit: 0,
transforms: undefined,
raw: undefined
},
logger: Logger { className: 'Cursor' },
s: {
numberOfRetries: 5,
tailableRetryInterval: 500,
currentNumberOfRetries: 5,
state: 0,
promiseLibrary: [Function: Promise],
explicitlyIgnoreSession: false
},
[Symbol(kCapture)]: false
}
And Mongo js docs tell me to connect to database over and over again
Those are simply examples. You can have a global client if you like (which would make sense for real applications).

Why mongoose's find() gives this weird result, with array of objects [duplicate]

This question already has answers here:
mongoose .find() method returns object with unwanted properties
(5 answers)
How can I display a JavaScript object?
(40 answers)
Closed 4 years ago.
I made a simple find query for mongoose, and it returns the result as well but it gives result in array of objects(this is not a problem), but it have array of objects, with objects contains its internal functions and properties, which I think not relevant to my need, as I only want the query result from database.
const Joi = require('joi');
const Session = require('../models/session.model');
exports.tokenUtility = async (req, res, next) => {
const {token, contactNumber, query} = req.body;
if(token) {
try{
const session = await Session.find({token});
console.log("Found Session", session);
} catch(error) {
next(error)
}
} else {
console.log("in token util, token is not present");
const generatedToken = (Math.random()*1e18).toString(36);
}
}
It gives me this result from output of Found Session
Found Session [ model {
'$__':
InternalCache {
strictMode: true,
selected: {},
shardval: undefined,
saveError: undefined,
validationError: undefined,
adhocPaths: undefined,
removing: undefined,
inserting: undefined,
saving: undefined,
version: undefined,
getters: {},
_id: 5ae31a2062728504f78ee860,
populate: undefined,
populated: undefined,
wasPopulated: false,
scope: undefined,
activePaths:
StateMachine {
paths:
{ token: 'init',
context: 'init',
contextArray: 'init',
_id: 'init',
__v: 'init' },
states:
{ ignore: {},
default: {},
init:
{ _id: true,
context: true,
contextArray: true,
token: true,
__v: true },
modify: {},
require: {} },
stateNames: [ 'require', 'modify', 'init', 'default', 'ignore' ] },
pathsToScopes: {},
session: null,
ownerDocument: undefined,
fullPath: undefined,
emitter:
EventEmitter {
_events: [Object: null prototype] {},
_eventsCount: 0,
_maxListeners: 0 },
'$options':
{ skipId: true,
isNew: false,
skipDefaults:
{ _id: true,
context: true,
contextArray: true,
token: true,
__v: true } } },
isNew: false,
errors: undefined,
_doc:
{ context: 'client',
contextArray:
[ 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: 'contextArray',
isMongooseArray: true,
validators: [],
_schema: SchemaArray {
casterConstructor: { [Function: SchemaString] schemaName: 'String' },
caster:
SchemaString {
enumValues: [],
regExp: null,
path: 'contextArray',
instance: 'String',
validators:
[ { validator: [Function],
message: 'Path `{PATH}` is required.',
type: 'required' } ],
setters: [],
getters: [],
options: { required: true },
_index: null,
isRequired: true,
requiredValidator: [Function],
originalRequiredValue: true },
'$isMongooseArray': true,
path: 'contextArray',
instance: 'Array',
validators: [],
setters: [],
getters: [],
options: { type: [ { type: [Function: String], required: true } ] },
_index: null,
defaultValue: { [Function: defaultFn] '$runBeforeSetters': true } } ],
_id: 5ae31a2062728504f78ee860,
token: '3agcnp5ufl8g',
__v: 0 },
'$init': true } ]

Can make post request to localhost using node-fetch, but unable to do so using Axios

I have tried making the same post request using node-fetch and axios.
var fetch = require('node-fetch');
var axios = require('axios');
async function fetchTest(host, port, body) {
const response = {
successMessage: '',
errorMessage: ''
}
try {
const streamResponse = await fetch(`${host}:${port}`, {
method: 'post',
body: JSON.stringify(body)
})
const jsonResponse = await streamResponse.json()
response.successMessage = jsonResponse;
} catch (error) {
response.errorMessage = error;
}
return response;
}
async function axiosTest(host, port, body) {
const response = {
successMessage: '',
errorMessage: ''
}
try {
const jsonResponse = await axios({
method: 'post',
url: `${host}:${port}`,
data: body
})
response.successMessage = jsonResponse;
} catch (error) {
response.errorMessage = error;
}
return response;
}
async function test() {
console.log(await fetchTest('http://127.0.0.1', '8801', { type: 'request', cmd: 'devices' }));
console.log(await axiosTest('http://127.0.0.1', '8801', { type: 'request', cmd: 'devices' }));
}
test();
The request made with node-fetch works nicely. The request made with axios returns (IP address redacted with ...) an error:
{ successMessage: '',
errorMessage:
{ Error: connect ECONNREFUSED ...:80
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1161:14)
errno: 'ECONNREFUSED',
code: 'ECONNREFUSED',
syscall: 'connect',
address: '...',
port: 80,
config:
{ adapter: [Function: httpAdapter],
transformRequest: [Object],
transformResponse: [Object],
timeout: 0,
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN',
maxContentLength: -1,
validateStatus: [Function: validateStatus],
headers: [Object],
method: 'post',
url: 'http://127.0.0.1:8801',
data: '{"type":"request","cmd":"devices"}' },
request:
Writable {
_writableState: [WritableState],
writable: true,
_events: [Object],
_eventsCount: 2,
_maxListeners: undefined,
_options: [Object],
_redirectCount: 1,
_redirects: [],
_requestBodyLength: 39,
_requestBodyBuffers: [],
_onNativeResponse: [Function],
_currentRequest: [ClientRequest],
_currentUrl: 'http://.../',
_isRedirect: true },
response: undefined } }
What might be the reason? Am I doing something wrong?
EDITED with more info requested in comment:
The axios request fails the same way if I comment out the node-fetch request.
The node-fetch request returns:
{
cmd: 'devices',
payload: { devices: [Array] },
type: 'response' },
}
Since I wrap the result in a response object, the console.log looks like
{
successMessage:
{
cmd: 'devices',
payload: { devices: [Array] },
type: 'response'
},
errorMessage: ''
}