node.js - NodeJS - 按 ID 查找不起作用

标签 node.js mongodb

我刚刚开始使用 NodeJs,我遵循了一些教程,但是在我尝试自己完成之后,我遇到了一些问题。

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

我的 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() :

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

但是,由于您正在搜索唯一的属性 (_id),因此您也可以使用 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/

相关文章:

javascript - 下载 billboard hot 100(但只有 50 个)mp3 文件

node.js - 如何在Electron的第二个窗口中隐藏菜单?

javascript - Node Js : How to read and update json file

c# - MongoDB 推送到空数组

debugging - 如何以编程方式检测nodejs中的 Debug模式?

c# - 如何在 C# MongoDB 驱动程序 v2.0 中获取连接状态?

javascript - 将 MongoDB 集合的数组字段更新为小写

javascript - Mongoose 更新条件匹配错误的对象

spring - 请使用“MongoMappingContext#setAutoIndexCreation(boolean)”或覆盖“MongoConfigurationSupport#autoIndexCreation()”以明确

javascript - 使用 Node SSL 将客户端证书设为可选(rejectUnauthorized : true doesn't do it? )