NodeJS - 通过Id找不到工作

时间:2017-05-21 19:57:08

标签: node.js mongodb

我刚开始使用NodeJs,我接受了一些教程,但在我尝试自己完成之后,我正在努力解决一些问题。

我正在尝试编辑保存到我的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"
}

我怎样才能获得标题和文字?

由于

2 个答案:

答案 0 :(得分:5)

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

答案 1 :(得分:1)

我建议你使用Mongoose,它可以让你做很多有用的东西,并且非常容易使用。在您的情况下,您可以为数据库定义模式,然后在其上应用所有mongoDB查询。

你的record.js看起来像那样:

var mongoose = require('mongoose');
var Record = mongoose.Schema({
    title: {type: String, required: true},
    text: {type: String, required: true}
});
module.exports = mongoose.model('Record', Record);

然后在新文件中,您可以导入模型并进行所需的所有查询:

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