npm pdfjs creates corrupted PDF files - node.js

I am trying to create PDF files with the npm library pdfjs https://www.npmjs.com/package/pdfjs . Once all the elements (paragraphs) of the file are append to the doc I create the file, but when opening it I have a message it says is corrupted.
When I use doc.end() to finish the document, says there is no function. So I used a promise and tried to use later on the information. But even when I get an object with all the data, I can't manage to make the .pdf file not corrupted.
This is the code I'm using:
const pdf = require('pdfjs')
const fs = require('fs')
function createPDF(data, options){
return new Promise((resolve, reject) => {
var doc = new pdf.Document({ font: require('pdfjs/font/Helvetica') });
var header = doc.header().table({ widths: [null, null], paddingBottom: 1*pdf.cm }).row()
header.cell().image('/images/logo.png', { height: 2*pdf.cm })
header.cell().text({ textAlign: 'right' })
.add('Example.')
.add('https://www.example.com', {
link: 'https://www.example.com',
underline: true,
color: 0x569cd6
})
doc.footer()
.pageNumber(async function(curr, total) { return curr + ' / ' + total }, { textAlign: 'center' });
resolve(doc)
});
}
var doc = createPDF();
doc.then(async (data) => {
data.pipe(fs.createWriteStream('output.pdf'))
console.log(data);
await data.end();
})
Log Data:
Document {
_readableState:
ReadableState {
objectMode: false,
highWaterMark: 16384,
buffer: BufferList { head: null, tail: null, length: 0 },
length: 0,
pipes:
WriteStream {
_writableState: [Object],
writable: true,
domain: null,
_events: [Object],
_eventsCount: 5,
_maxListeners: undefined,
path: 'output.pdf',
fd: null,
flags: 'w',
mode: 438,
start: undefined,
autoClose: true,
pos: undefined,
bytesWritten: 0 },
pipesCount: 1,
flowing: true,
ended: false,
endEmitted: false,
reading: false,
sync: true,
needReadable: false,
emittedReadable: false,
readableListening: false,
resumeScheduled: true,
paused: false,
emitClose: true,
destroyed: false,
defaultEncoding: 'utf8',
awaitDrain: 0,
readingMore: false,
decoder: null,
encoding: null },
readable: true,
domain: null,
_events:
{ read: { [Function: bound onceWrapper] listener: [Function] },
end: { [Function: bound onceWrapper] listener: [Function: onend] },
data: [Function: ondata] },
_eventsCount: 3,
_maxListeners: undefined,
version: '1.6',
info: { id: '34d7f55c-5961-4caf-9814-1902b98bee3c' },
width: 595.296,
height: 841.896,
_nextObjectId: 4,
_xref: PDFXref { objects: [], trailer: null },
_reading: false,
_length: 0,
_pending:
[ [Function],
[ [Function], [Array], [Array], [Function] ],
[Function],
[Function],
[Function],
[Function],
current: Promise { <pending> } ],
defaultFont:
AFMFont {
_data:
{ fontName: 'Helvetica',
fullName: 'Helvetica',
familyName: 'Helvetica',
italicAngle: 0,
characterSet: 'ExtendedRoman',
fontBBox: [Array],
underlinePosition: -100,
underlineThickness: 50,
capHeight: 718,
xHeight: 523,
ascender: 718,
descender: -207,
kerning: [Object],
widths: [Array] },
lineGap: 231,
parent: [Circular] },
defaultFontSize: 11,
defaultColor: [ 0, 0, 0 ],
defaultLineHeight: 1.15,
_fonts: { '/F1': { f: [Object], o: [Object] } },
_xobjects: {},
_pageFonts: {},
_annotations: [],
_aliases: AliasGenerator { nextId: { F: 2 }, blocked: Set {} },
_mapping: WeakMap {},
_currentContent: null,
_contents: [],
_contentObjCreator: null,
_finalize: [],
_template: null,
_footer: null,
_header: null,
paddingTop: 20,
paddingBottom: 20,
paddingLeft: 20,
paddingRight: 20,
_cursor:
Cursor {
width: 555.296,
height: 801.896,
x: 20,
startX: 20,
y: 821.896,
startY: 821.896,
_bottom: 20,
bottomOffset: 0 },
_pages: [ toString: [Function] ],
_pagesObj:
PDFObject {
id: 2,
rev: 0,
properties: PDFDictionary { dictionary: [Object] },
reference: PDFReference { object: [Getter] },
content: 'stream\n!!!Djz!WW3#D/OH9;Fa%r=BSfM#MB(Z!#knQ!$hOd#:O#tzzzz!!!!"zz!!)`D!!*\'"!!(J"z\'&psr`WC#h?J?20S8TbAzzzzzzz!!!!1A7]gl!!!
$f!!!"E#TZc:!!!&8!!!!5#T65m!!!&L!!!95B2hbr!!!&L!!!95E`>q(!!!&L!!!95A8Pjf!!!>`!!!"TB38;?!!!#>!!!!5CisT/!!!#R!!!!5D.R-s!!!#f!!!!E#V]q)!!!A5!
!!!5E`cIJ!!!AI!!!!5FCerq!!!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zzzzzzzzzzzz=BSfMz!!)`D!!*\'"!!(J"FCf]=z6Z6phEbT0"F<F.mFCfK1#<?4%DII
?(6Z6dZEZd_fDKB`:FD5l7/0H]%0KB+5F(R3`z!!*Kr!!!2[s8V[;!!!7g!!)tYs8Vtis8W%l!!!,U!!\'fW~>\nendstream\n' },
_currentColorSpace: '/CS1',
_doc: [Circular],
_parent: [Circular],
_ended: false,
_current:
Footer {
_doc: [Circular],
_parent: [Circular],
_cursor:
ClonedCursor {
width: 555.296,
height: 801.896,
bottomOffset: 0,
startX: 20,
startY: 821.896,
_root: [Object] },
_ended: false,
_current: null,
_pending:
[ [Function],
[Array],
[Function],
[Function],
[Function],
[Function],
current: [Object] ],
_objects: [],
_pageNumbers: [] } }
It looks like the content is there but can't manage to get it. And whe await data.end(); is run, it show the next error log show:
TypeError: Invalid value used as weak map key TypeError: Invalid value used as weak map key
at WeakMap.set (native)
at Document._useXObject (/home/developer1/Projects/bfreit_website/node_modules/pdfjs/lib/document.js:255:21)
at module.exports (/home/developer1/Projects/bfreit_website/node_modules/pdfjs/lib/image/render.js:16:23)
at _pending.push (/home/developer1/Projects/bfreit_website/node_modules/pdfjs/lib/fragment.js:143:30)
at Document._next (/home/developer1/Projects/bfreit_website/node_modules/pdfjs/lib/document.js:169:36)
at _pending.current.next.then (/home/developer1/Projects/bfreit_website/node_modules/pdfjs/lib/document.js:172:19)
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:188:7)
The expected output is a correct .pdf file. But even when my output is a .pdf file, it is corrupted.
Unable to open document “file:///home/developer1/Projects/pdf/output.pdf”.
Error when trying to open the file:
PDF document is damaged
If you can help me either solving this, or with a library of your knowledge that it works will be bomb.

I could not found a solution for the pdfjs library. But I found a library that worked better in my project. It is really easy to work with.
Short Example:
const pdf = require('pdfkit');
const fs = require('fs');
const doc = new pdf();
doc.pipe(fs.createWriteStream('/my/path'));
doc.fontSize(10).text('Fontsize 10')
doc
.fontSize(18)
.text('Font Size 18 aligned right', {align: 'right'});
doc.moveDown();
doc.fontSize(14).text('Font size 14 aligned center',{align:'center' })
doc.end();

Related

Unable to retrieve data from mongodb to Node JS [duplicate]

This question already has answers here:
nodejs get find results in mongodb
(2 answers)
Closed 3 years ago.
Trying to fetch data from MongoDB to Node JS
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("Mydb");
console.log("Hello")
dbo.collection("POC_DB").find({}, function(err, result) {
if (err) throw err;
console.log(result);
db.close();
});
});
If I make it as "result.name" then I am getting output as undefined.
I am suspecting that it could be the value in raw parameter given in the actual output.
Actual Cursor Output
Cursor {
_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,
destroyed: false,
defaultEncoding: 'utf8',
awaitDrain: 0,
readingMore: false,
decoder: null,
encoding: null },
readable: true,
_events: {},
_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: 'Mydb', collection: 'POC_DB' },
cmd:
{ find: 'Mydb.POC_DB',
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,
reconnect: true } },
pool: null,
server: null,
disconnectHandler: undefined,
bson: undefined,
ns: 'Mydb.POC_DB',
namespace: MongoDBNamespace { db: 'Mydb', collection: 'POC_DB' },
cmd:
{ find: 'Mydb.POC_DB',
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: {},
_eventsCount: 0,
_maxListeners: undefined,
s: [Object],
serverConfig: [Getter],
bufferMaxEntries: [Getter],
databaseName: [Getter] },
promiseLibrary: [Function: Promise] },
topology:
Server {
_events:
{ serverOpening: [Function],
serverDescriptionChanged: [Function],
serverHeartbeatStarted: [Function],
serverHeartbeatSucceeded: [Function],
serverHeartbeatFailed: [Function],
serverClosed: [Function],
topologyOpening: [Function],
topologyClosed: [Function],
topologyDescriptionChanged: [Function],
commandStarted: [Function],
commandSucceeded: [Function],
commandFailed: [Function],
joined: [Function],
left: [Function],
ping: [Function],
ha: [Function],
authenticated: [Function],
error: [Array],
timeout: [Array],
close: [Array],
parseError: [Array],
open: [Array],
fullsetup: [Array],
all: [Array],
reconnect: [Array] },
_eventsCount: 25,
_maxListeners: Infinity,
clientInfo:
{ driver: [Object],
os: [Object],
platform: 'Node.js v10.13.0, LE' },
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] } },
cursorState:
{ cursorId: null,
cmd:
{ find: 'Mydb.POC_DB',
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,
reconnect: true },
logger: Logger { className: 'Cursor' },
s:
{ numberOfRetries: 5,
tailableRetryInterval: 500,
currentNumberOfRetries: 5,
state: 0,
promiseLibrary: [Function: Promise],
currentDoc: null,
explicitlyIgnoreSession: false } }
.find() returns the result as an array if it exists so you have to get like result[0].name to get the data.
You should also check the length of the array in order not to get the out of bound exception.
According to MongoDB, if you are using find() method, they will return an array of document. So you need to access to that array to get your result (array[index].name). If you want to find just one document, you can use findOne() method.

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

Selection in mongoDb return weird stuff

I have the following selection query:
student.findCourses = (fcallback) => {
global.db.collection('students').find(({}, { "courses.courseName": true, _id: false }), (err, result) => {
if (err) {
var jError = { "status": "error", "message": "ERROR -> student.js -> 001" }
console.log(jError)
return fcallback(true, jError)
}
var jOk = { "status": "ok", "message": "student.js -> found -> 000" }
console.log(jOk)
console.log(result);
return fcallback(false, jOk)
})
}
And this is what I get in the console. I get status ok however it seems odd to me the response.
{ status: 'ok', message: 'student.js -> found -> 000' }
Cursor {
pool: null,
server: null,
disconnectHandler:
Store {
s: { storedOps: [], storeOptions: [Object], topology: [Object] },
length: [Getter] },
bson: BSON {},
ns: 'kea.students',
cmd:
{ find: 'kea.students',
limit: 0,
skip: 0,
query: { 'courses.courseName': true, _id: false },
readPreference: ReadPreference { preference: 'primary', tags: undefined, options: [Object] },
slaveOk: true },
options:
{ readPreference: ReadPreference { preference: 'primary', tags: undefined, options: [Object] },
skip: 0,
limit: 0,
raw: undefined,
hint: null,
timeout: undefined,
slaveOk: true,
db:
Db {
domain: null,
_events: {},
_eventsCount: 0,
_maxListeners: undefined,
s: [Object],
serverConfig: [Getter],
bufferMaxEntries: [Getter],
databaseName: [Getter] },
promiseLibrary: [Function: Promise],
disconnectHandler: Store { s: [Object], length: [Getter] } },
topology:
Server {
domain: null,
_events:
{ reconnect: [Function: reconnectHandler],
reconnectFailed: [Function: reconnectFailedHandler],
serverDescriptionChanged: [Function],
serverHeartbeatStarted: [Function],
serverHeartbeatSucceeded: [Function],
serverHeartbeatFailed: [Function],
serverOpening: [Function],
serverClosed: [Function],
topologyOpening: [Function],
topologyClosed: [Function],
topologyDescriptionChanged: [Function],
attemptReconnect: [Function],
monitoring: [Function],
timeout: [Function],
error: [Object],
close: [Function],
destroy: [Function: destroyHandler] },
_eventsCount: 17,
_maxListeners: undefined,
id: 0,
s:
{ options: [Object],
logger: [Object],
Cursor: [Object],
bson: BSON {},
pool: [Object],
disconnectHandler: [Object],
monitoring: true,
inTopology: false,
monitoringInterval: 5000,
topologyId: -1,
serverDescription: [Object],
topologyDescription: [Object] },
ismaster:
{ ismaster: true,
maxBsonObjectSize: 16777216,
maxMessageSizeBytes: 48000000,
maxWriteBatchSize: 1000,
localTime: 2017-11-06T19:51:35.856Z,
maxWireVersion: 5,
minWireVersion: 0,
readOnly: false,
ok: 1 },
lastIsMasterMS: 10,
monitoringProcessId:
Timeout {
_called: false,
_idleTimeout: 5000,
_idlePrev: [Object],
_idleNext: [Object],
_idleStart: 657,
_onTimeout: [Function],
_timerArgs: undefined,
_repeat: null },
initalConnect: false,
wireProtocolHandler: WireProtocol { legacyWireProtocol: WireProtocol {} },
_type: 'server',
clientInfo:
{ driver: [Object],
os: [Object],
platform: 'Node.js v6.11.4, LE, mongodb-core: 2.1.17' },
lastUpdateTime: 0,
lastWriteDate: 0,
staleness: 0 },
cursorState:
{ cursorId: null,
cmd:
{ find: 'kea.students',
limit: 0,
skip: 0,
query: [Object],
readPreference: [Object],
slaveOk: true },
documents: [],
cursorIndex: 0,
dead: false,
killed: false,
init: false,
notified: false,
limit: 0,
skip: 0,
batchSize: 1000,
currentLimit: 0,
transforms: undefined },
logger: Logger { className: 'Cursor' },
_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,
defaultEncoding: 'utf8',
ranOut: false,
awaitDrain: 0,
readingMore: false,
decoder: null,
encoding: null },
readable: true,
domain: null,
_events: {},
_eventsCount: 0,
_maxListeners: undefined,
s:
{ numberOfRetries: 5,
tailableRetryInterval: 500,
currentNumberOfRetries: 5,
state: 0,
streamOptions: {},
bson: BSON {},
ns: 'kea.students',
cmd:
{ find: 'kea.students',
limit: 0,
skip: 0,
query: [Object],
readPreference: [Object],
slaveOk: true },
options:
{ readPreference: [Object],
skip: 0,
limit: 0,
raw: undefined,
hint: null,
timeout: undefined,
slaveOk: true,
db: [Object],
promiseLibrary: [Function: Promise],
disconnectHandler: [Object] },
topology:
Server {
domain: null,
_events: [Object],
_eventsCount: 17,
_maxListeners: undefined,
id: 0,
s: [Object],
ismaster: [Object],
lastIsMasterMS: 10,
monitoringProcessId: [Object],
initalConnect: false,
wireProtocolHandler: [Object],
_type: 'server',
clientInfo: [Object],
lastUpdateTime: 0,
lastWriteDate: 0,
staleness: 0 },
topologyOptions:
{ host: 'localhost',
port: 27017,
disconnectHandler: [Object],
cursorFactory: [Object],
reconnect: true,
emitError: true,
size: 5,
socketOptions: {},
socketTimeout: 360000,
connectionTimeout: 30000,
clientInfo: [Object],
readPreference: [Object],
promiseLibrary: [Function: Promise],
bson: BSON {} },
promiseLibrary: [Function: Promise],
currentDoc: null },
sortValue: undefined }
at Module.load (module.js:487:32)
I want to get only the data from the query, which is the following:
{ "courses": [
{
"courseName": "Web-development"
},
{
"courseName": "Databases"
},
{
"courseName": "Interface-Design"
}
]
}
I am not sure if there is something wrong with my query or with the way I am asking for the result?
When I do an insertion indeed I say console.log(JSON.stringify(result.ops)) which gives me only the inserted data, but if I use that for the selection it gives me undefined.
That´s why I am not sure if the query is actually working or you just ask in a different way to get the selected data?
From documentation. find return a cursor
https://docs.mongodb.com/manual/reference/method/db.collection.find/
This is what you see in console
In order to get results you can use toArray
https://docs.mongodb.com/manual/reference/method/cursor.toArray/
global.db.collection('students')
.find(({}, { "courses.courseName": 1, _id: 0}).toArray()
.then((data) => {//you will have your result here})
.catch(err => {//error if something wrong});
or in old way
global.db.collection('students')
.find(({}, { "courses.courseName": 1, _id: 0})
.toArray((err,data) => {//do stuff here});
Hope this helps.

NodeJS - find by Id not working

i am just starting with NodeJs, I followed a few tutorials but after I try to do it by myself I am struggling with some things.
I'm trying to edit a post saved into my Mlab (Mongo) database. But I can't reach my values even if I have a good response:
My server.js code
app.get('/post/:id/edit', function(req,res){
console.log(req.params.id)
db.collection('posts').find({_id:ObjectId(req.params.id)},{},{}, function(err, result){
console.log(result)
if (err) return console.log(err)
res.render('edit.ejs', {post: result})
})
})
As a result I'm getting the below: (no text or title as expected)
Readable {
pool: null,
server: null,
disconnectHandler:
{ s: { storedOps: [], storeOptions: [Object], topology: [Object] },
length: [Getter] },
bson: {},
ns: 'analistafuncionalblog.posts',
cmd:
{ find: 'analistafuncionalblog.posts',
limit: 0,
skip: 0,
query: { _id: 5921bf9aff2e7524b4552480 },
readPreference: { preference: 'primary', tags: undefined, options: [Object] },
slaveOk: true,
fields: {} },
options:
{ readPreference: { preference: 'primary', tags: undefined, options: [Object] },
skip: 0,
limit: 0,
raw: undefined,
hint: null,
timeout: undefined,
slaveOk: true,
db:
EventEmitter {
domain: null,
_events: {},
_eventsCount: 0,
_maxListeners: undefined,
s: [Object],
serverConfig: [Getter],
bufferMaxEntries: [Getter],
databaseName: [Getter] },
promiseLibrary: [Function: Promise],
disconnectHandler: { s: [Object], length: [Getter] } },
topology:
EventEmitter {
domain: null,
_events:
{ reconnect: [Function],
reconnectFailed: [Function],
timeout: [Function],
error: [Object],
close: [Function],
destroy: [Function],
serverDescriptionChanged: [Function],
serverHeartbeatStarted: [Function],
serverHeartbeatSucceeded: [Function],
serverHeartbeatFailed: [Function],
serverOpening: [Function],
serverClosed: [Function],
topologyOpening: [Function],
topologyClosed: [Function],
topologyDescriptionChanged: [Function],
attemptReconnect: [Function],
monitoring: [Function] },
_eventsCount: 17,
_maxListeners: undefined,
id: 0,
s:
{ options: [Object],
logger: [Object],
Cursor: [Object],
bson: {},
pool: [Object],
disconnectHandler: [Object],
monitoring: true,
inTopology: false,
monitoringInterval: 5000,
topologyId: -1 },
ismaster:
{ hosts: [Object],
setName: 'rs-ds149221',
setVersion: 1,
ismaster: true,
secondary: false,
primary: 'ds149221-a.mlab.com:49221',
me: 'ds149221-a.mlab.com:49221',
electionId: 7fffffff0000000000000001,
maxBsonObjectSize: 16777216,
maxMessageSizeBytes: 48000000,
maxWriteBatchSize: 1000,
localTime: Sun May 21 2017 16:50:58 GMT-0300 (Argentina Standard Time),
maxWireVersion: 4,
minWireVersion: 0,
ok: 1 },
lastIsMasterMS: 168,
monitoringProcessId:
{ _called: false,
_idleTimeout: 5000,
_idlePrev: [Object],
_idleNext: [Object],
_idleStart: 17129,
_onTimeout: [Function],
_repeat: null },
initalConnect: false,
wireProtocolHandler: { legacyWireProtocol: {} },
_type: 'server',
clientInfo:
{ driver: [Object],
os: [Object],
platform: 'Node.js v4.4.7, LE, mongodb-core: 2.1.10' },
lastUpdateTime: 0,
lastWriteDate: 0,
staleness: 0 },
cursorState:
{ cursorId: null,
cmd:
{ find: 'analistafuncionalblog.posts',
limit: 0,
skip: 0,
query: [Object],
readPreference: [Object],
slaveOk: true,
fields: {} },
documents: [],
cursorIndex: 0,
dead: false,
killed: false,
init: false,
notified: false,
limit: 0,
skip: 0,
batchSize: 1000,
currentLimit: 0,
transforms: undefined },
logger: { className: 'Cursor' },
_readableState:
ReadableState {
objectMode: true,
highWaterMark: 16,
buffer: [],
length: 0,
pipes: null,
pipesCount: 0,
flowing: null,
ended: false,
endEmitted: false,
reading: false,
sync: true,
needReadable: false,
emittedReadable: false,
readableListening: false,
resumeScheduled: false,
defaultEncoding: 'utf8',
ranOut: false,
awaitDrain: 0,
readingMore: false,
decoder: null,
encoding: null },
readable: true,
domain: null,
_events: {},
_eventsCount: 0,
_maxListeners: undefined,
s:
{ numberOfRetries: 5,
tailableRetryInterval: 500,
currentNumberOfRetries: 5,
state: 0,
streamOptions: {},
bson: {},
ns: 'analistafuncionalblog.posts',
cmd:
{ find: 'analistafuncionalblog.posts',
limit: 0,
skip: 0,
query: [Object],
readPreference: [Object],
slaveOk: true,
fields: {} },
options:
{ readPreference: [Object],
skip: 0,
limit: 0,
raw: undefined,
hint: null,
timeout: undefined,
slaveOk: true,
db: [Object],
promiseLibrary: [Function: Promise],
disconnectHandler: [Object] },
topology:
EventEmitter {
domain: null,
_events: [Object],
_eventsCount: 17,
_maxListeners: undefined,
id: 0,
s: [Object],
ismaster: [Object],
lastIsMasterMS: 168,
monitoringProcessId: [Object],
initalConnect: false,
wireProtocolHandler: [Object],
_type: 'server',
clientInfo: [Object],
lastUpdateTime: 0,
lastWriteDate: 0,
staleness: 0 },
topologyOptions:
{ host: 'ds149221.mlab.com',
port: 49221,
disconnectHandler: [Object],
cursorFactory: [Object],
reconnect: true,
emitError: true,
size: 5,
socketOptions: {},
socketTimeout: 30000,
connectionTimeout: 30000,
clientInfo: [Object],
readPreference: [Object],
promiseLibrary: [Function: Promise],
bson: {} },
promiseLibrary: [Function: Promise],
currentDoc: null },
sortValue: undefined }
In my Mlab I keep my collection like:
{
"_id": {
"$oid": "5921bf9aff2e7524b4552480"
},
"title": "Prueba 1",
"text": "Ezequiel prueba texto"
}
how can I get the title and the text?
Thanks
collection.find() returns a cursor, which you need to read from in order to get the actual documents from the database.
For that, you can use cursor.toArray():
db.collection('posts').find({
_id : ObjectId(req.params.id)
}).toArray(function(err, results) {
...
});
However, since you're searching on a unique property (_id), you could also use collection.findOne():
db.collection('posts').findOne({ _id : ObjectId(req.params.id) }, function(err, post) {
...
});
I suggest you to use Mongoose, it allows you to do a lot of useful things, and is very easy to use. In your case, you can define a schema for the db and then apply all the mongoDB query on it.
Your record.js looks like that:
var mongoose = require('mongoose');
var Record = mongoose.Schema({
title: {type: String, required: true},
text: {type: String, required: true}
});
module.exports = mongoose.model('Record', Record);
Then in a new file, you can import the model and make all the query that you need:
var mongoose = require('mongoose');
var Record = require('./record');
mongoose.connect('mongodb://localhost/YOURDB');
app.get('/post/:id/edit', function(req,res){
console.log(req.params.id)
Record.findById(req.params.id, function(err, record){
if(err) throw err;
else return res.render('edit.ejs', {post: result});
});
});

Mongoose does not query my collection using .find() method

I connected to the collection and then began my query on the collectionto find all documents with this query. However when I log the result I get a Readable object, which I assume is a stream. I used some stream methods on it but it only returns one document. I'm not sure why it doesn't return json.
const path = require('path'),
User = require(path.join(__dirname, '../models/user.js')),
Card = require(path.join(__dirname, '../models/card.js')),
mongoose = require('mongoose');
module.exports = {
get: (req, res) => {
const foo = mongoose.connection.db.collection('foo');
Card.find({ _id: {$in: req.user.cards } },
{ name: 1,
bank: 1 }).exec(function(err, cards) {
if (err) throw err;
// Problem: does not return documents or error
foo.find({ bank: 'chase'}, { name: 1, bank: 1, value: 1 }, function(err, bonus) {
if (err) throw err;
console.log(bonus);
});
});
}
}
Here is the output. I don't think my query is executing but I don't know where to go from here.
Readable {
pool: null,
server: null,
disconnectHandler:
{ s: { storedOps: [], storeOptions: [Object], topology: [Object] },
length: [Getter] },
bson: {},
ns: 'kard_development.kard_bonus',
cmd:
{ find: 'kard_development.kard_bonus',
limit: 0,
skip: 0,
query: { bank: 'Chase' },
slaveOk: false },
options:
{ skip: 0,
limit: 0,
raw: undefined,
hint: null,
timeout: undefined,
slaveOk: false,
db:
EventEmitter {
domain: null,
_events: [Object],
_eventsCount: 6,
_maxListeners: undefined,
s: [Object],
serverConfig: [Getter],
bufferMaxEntries: [Getter],
databaseName: [Getter],
_listening: true },
promiseLibrary: [Function: Promise],
disconnectHandler: { s: [Object], length: [Getter] } },
topology:
EventEmitter {
domain: null,
_events:
{ reconnect: [Function],
timeout: [Object],
error: [Object],
close: [Function],
destroy: [Object],
serverDescriptionChanged: [Function],
serverHeartbeatStarted: [Function],
serverHeartbeatSucceeded: [Function],
serverHearbeatFailed: [Function],
serverOpening: [Function],
serverClosed: [Function],
topologyOpening: [Function],
topologyClosed: [Function],
topologyDescriptionChanged: [Function] },
_eventsCount: 14,
_maxListeners: undefined,
s:
{ options: [Object],
callbacks: [Object],
logger: [Object],
state: 'connected',
reconnect: true,
reconnectTries: 30,
reconnectInterval: 1000,
emitError: true,
currentReconnectRetry: 30,
ismaster: [Object],
readPreferenceStrategies: undefined,
authProviders: [Object],
id: 0,
topologyId: -1,
tag: undefined,
disconnectHandler: [Object],
monitoring: false,
haInterval: 10000,
wireProtocolHandler: [Object],
Cursor: [Object],
bsonInstance: {},
inquireServerStateTimeout: null,
bson: {},
pool: [Object],
isMasterLatencyMS: 8,
inTopology: false,
serverDetails: [Object],
serverDescription: null,
topologyDescription: null },
hashedName: '1309e35791f04f1f4fc35d5e683e81d350dd04f4',
name: [Getter],
bson: [Getter],
wireProtocolHandler: [Getter],
id: [Getter] },
cursorState:
{ cursorId: null,
cmd:
{ find: 'kard_development.kard_bonus',
limit: 0,
skip: 0,
query: [Object],
slaveOk: false },
documents: [],
cursorIndex: 0,
dead: false,
killed: false,
init: false,
notified: false,
limit: 0,
skip: 0,
batchSize: 1000,
currentLimit: 0,
transforms: undefined },
callbacks: null,
logger: { className: 'Cursor' },
_readableState:
ReadableState {
objectMode: true,
highWaterMark: 16,
buffer: [],
length: 0,
pipes: null,
pipesCount: 0,
flowing: null,
ended: false,
endEmitted: false,
reading: false,
sync: true,
needReadable: false,
emittedReadable: false,
readableListening: false,
resumeScheduled: false,
defaultEncoding: 'utf8',
ranOut: false,
awaitDrain: 0,
readingMore: false,
decoder: null,
encoding: null },
readable: true,
domain:
Domain {
domain: null,
_events: { error: [Function] },
_eventsCount: 1,
_maxListeners: undefined,
members: [] },
_events: {},
_eventsCount: 0,
_maxListeners: undefined,
s:
{ numberOfRetries: 5,
tailableRetryInterval: 500,
currentNumberOfRetries: 5,
state: 0,
streamOptions: {},
bson: {},
ns: 'kard_development.kard_bonus',
cmd:
{ find: 'kard_development.kard_bonus',
limit: 0,
skip: 0,
query: [Object],
slaveOk: false },
options:
{ skip: 0,
limit: 0,
raw: undefined,
hint: null,
timeout: undefined,
slaveOk: false,
db: [Object],
promiseLibrary: [Function: Promise],
disconnectHandler: [Object] },
topology:
EventEmitter {
domain: null,
_events: [Object],
_eventsCount: 14,
_maxListeners: undefined,
s: [Object],
hashedName: '1309e35791f04f1f4fc35d5e683e81d350dd04f4',
name: [Getter],
bson: [Getter],
wireProtocolHandler: [Getter],
id: [Getter] },
topologyOptions:
{ socketOptions: {},
auto_reconnect: true,
host: 'localhost',
port: 27017,
cursorFactory: [Object],
reconnect: true,
emitError: true,
size: 5,
disconnectHandler: [Object],
bson: {},
messageHandler: [Function],
wireProtocolHandler: [Object] },
promiseLibrary: [Function: Promise],
currentDoc: null },
sortValue: undefined }
If you're using Mongoose, it's known as an ODM for MongoDB, which is great if you're using of models/schemas, but for simple queries over a collection its a little weird. If you look at the Mongoose API http://mongoosejs.com/docs/api.html, the find methods are only available to models and queries, which is why your first find works, you are using the Card model.
However if you want to do a query on your collection, like you have in this line:
const foo = mongoose.connection.db.collection('foo');
It won't quite work as mongoose connection objects don't have a .find() method. One thing you can do is use the native MongoDB driver for Node, sort of what #dvlsg was alluding to in the comments, and you'll probably get what you are looking for.

Resources