db.collection findOne by id 运行但不返回

db.collection findOne by id runs but doesn't return

本文关键字:返回 运行 id collection findOne by db      更新时间:2023-09-26

我正在使用节点mongo db本机模块,但我在使用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);
});

结果将是空的,这没有意义。我错过了什么吗?

谢谢。

尝试将_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);
});