Ezequiel Ramiro Ezequiel Ramiro -4 years ago 99
Node.js Question

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

Answer Source

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) {
  ...
});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download