id运行db.collection findOne但没有返回

时间:2016-02-08 19:20:47

标签: javascript node.js mongodb

我正在使用node mongo db native module并且我对findOne感到困难。

当我跑步时:

let collection = db.collection('eventschemas')

collection.find({}).toArray(function(error, result) {
  if (error) console.log(error);
  console.log(result);
});

结果将是:

[ { _id: 56b644a1bc8f66ce59322b38,
    type: 'events',
    attributes: 
     { hiw: [Object],
       title: 'Pub Crawl',
       'meeting-point': 'Ponto de encontro',
       information: '1h de Open Bar',
       'women-price': 40,
       'men-price': 60,
       end: Sat Feb 13 2016 17:08:00 GMT-0200 (BRST),
       start: Sat Feb 13 2016 17:07:59 GMT-0200 (BRST),
       'updated-at': Sat Feb 06 2016 17:08:54 GMT-0200 (BRST),
       'created-at': Sat Feb 06 2016 17:08:17 GMT-0200 (BRST),
       'is-active': true },
    __v: 0 } ]

我只有一个事件,所以它是正确的结果。但是当我跑步时:

let collection = db.collection('eventschemas')

collection.findOne({ _id: '56b644a1bc8f66ce59322b38' }, function(error, result) {
  if (error) console.log(error);
  console.log(result);
});

结果将为null,没有意义。我错过了什么吗?

感谢。

1 个答案:

答案 0 :(得分:2)

尝试将_id字符串包裹在 ObjectID() 中:

var ObjectID = require('mongodb').ObjectID,
    id = new ObjectID('56b644a1bc8f66ce59322b38'); // wrap in ObjectID

let collection = db.collection('eventschemas')

collection.findOne({ _id: id }, function(error, result) {
    if (error) console.log(error);
    console.log(result);
});