node.js - 类型错误 : Cannot read property 'findOne' of undefined

标签 node.js mongodb rest

代码如下

var mongo = require('mongodb');

var databaseName = 'Starter',
    collectionName = 'wines';

var Server = mongo.Server,
    Db = mongo.Db,
    BSON = mongo.BSONPure;

db = new Db(databaseName, server);

db.open(function(err, db) {
  if(!err) {
    console.log("Connected to 'winedb' database");
    db.collection(collectionName, {strict:true}, function(err, collection) {
        if (err) {
            console.log("The 'wines' collection doesn't exist. Creating it with sample data...");
            populateDB();
        }
    });
  }
});

exports.findById = function(req, res) {
  var id = req.params.id;
  console.log('Retrieving wine: ' + id);

  db.collection(collectionName, function(err, collection) {
      collection.findOne({'_id':new BSON.ObjectID(id)}, function(err, item) {
          res.send(item);
      });
  });

};

这些代码基于带有 mongoDB 的 nodejs 的 restful api 示例。 但是,它似乎无法识别函数findOne。有人可以指出问题吗?

错误信息:

TypeError: Cannot read property 'findOne' of undefined

最佳答案

findOne is deprecated in the latest version of mongodb@2.x

https://github.com/mongodb/node-mongodb-native/blob/2.0/lib/collection.js

您可以改用此查询

find(query).limit(1).next(function(err, doc){
   // handle data
})

关于node.js - 类型错误 : Cannot read property 'findOne' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39394582/

相关文章:

javascript - 使用 Axios 的 Amazon S3 远程文件上传

java - Spring MVC 请求映射 - 完整请求 URI

javascript - Node.js 和浏览器中的 setTimeout/setInterval 有多准确?

node.js - 如何使用 puppeteer 最大化浏览器窗口?

javascript - getElementsByTagName 不起作用

rest - Postman 或 Chrome 可以显示 REST 流输出吗?

google-app-engine - 使用 REST 接口(interface)进行内部 Google AppEngine 查询

mongodb - 如何通过 MongoDB 和 Express.js 对集合中的所有文档进行计数并在 Controller 中使用 cont?

node.js - 按 mongoDB (mongoose) 中的虚拟字段排序

mongodb - Doctrine MongoDB delete 仅引用 onRemove