按ID查找不起作用

按ID查找不起作用

我只是从NodeJ入手,我遵循了一些教程,但是在我自己尝试做完之后,我在做一些事情。

我正在尝试编辑保存到我的Mlab(Mongo)数据库中的帖子。但是,即使我做出了很好的回应,我也无法实现自己的价值观:

我的server.js代码

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


结果,我得到以下信息:(没有预期的文本或标题)

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 }


在我的Mlab中,我保持收藏如下:

{
    "_id": {
        "$oid": "5921bf9aff2e7524b4552480"
    },
    "title": "Prueba 1",
    "text": "Ezequiel prueba texto"
}


如何获得标题和文本?

谢谢

最佳答案

collection.find()返回cursor,您需要从中读取cursor.toArray()才能从数据库中获取实际文档。

为此,您可以使用_id

db.collection('posts').find({
  _id : ObjectId(req.params.id)
}).toArray(function(err, results) {
  ...
});


但是,由于要搜索的是唯一属性(collection.findOne()),因此也可以使用:

db.collection('posts').findOne({ _id : ObjectId(req.params.id) }, function(err, post) {
  ...
});

关于node.js - NodeJS-按ID查找不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44101202/

10-11 07:18