Mongo db.getCollection 不是函数

apa*_*pat 5 javascript mongodb

我一直在尝试在我的计算机上设置一个基本的 MongoDB 示例。但我不能得到太多的工作。

当我尝试从我的数据库中检索一个集合(只有一个)时,出现错误:

类型错误:db.getCollection 不是函数

如果我尝试直接通过它的名称访问我的收藏,我会收到错误

类型错误:无法读取未定义的属性“插入”

我在 mLab 上在线创建了我的数据库,因此我知道该集合存在。

这是我的 server.js:

const express        = require('express');
const MongoClient    = require('mongodb').MongoClient;
const bodyParser     = require('body-parser');
const app            = express();
const db             = require('./db');
const port = 8000;

app.use(bodyParser.urlencoded({ extended: true }));

MongoClient.connect(db.url, (err, database) => {
  if (err) return console.log(err)
  require('./app/routes')(app, database);
  app.listen(port, () => {
    console.log('We are live on ' + port );
  });               
})
Run Code Online (Sandbox Code Playgroud)

这是我的路线:

module.exports = function(app, db) {
  app.post('/notes', (req, res) => {
    const note = { text: req.body.body, title: req.body.title };
    db.getCollection('facts').insert(note, (err, result) => {
      if (err) { 
        res.send({ 'error': 'An error has occurred' }); 
      } else {
        res.send(result.ops[0]);
      }
    });
  });
};
Run Code Online (Sandbox Code Playgroud)

为什么我无法访问 getCollection() 函数?

Avi*_*viD 5

因为在 mongodb js 库(正确名称是node-mongodb-native)中.getCollection()不存在作为db对象上的方法。

而是调用db.collection()(或其他类似方法之一)。

collection(name, options, callback){Collection}

获取特定集合(包含实际集合信息)。如果应用程序不使用严格模式,您可以通过以下方式使用它而不需要回调:const collection = db.collection('mycollection');