【问题标题】:Mongo db.getCollection is not a functionMongo db.getCollection 不是函数
【发布时间】:2018-05-23 18:01:51
【问题描述】:

我一直在尝试在我的计算机上设置一个基本的 MongoDB 示例。 但我没有太多工作要做。

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

TypeError: db.getCollection 不是函数

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

TypeError: 无法读取未定义的属性“插入”

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

这是我的路线:

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

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

【问题讨论】:

标签: javascript mongodb


【解决方案1】:

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

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

collection(name, options, callback){Collection}

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

【讨论】:

    猜你喜欢
    • 2020-09-12
    • 2016-04-30
    • 1970-01-01
    • 1970-01-01
    • 2022-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-05
    相关资源
    最近更新 更多